Android 图片优化

来源:互联网 发布:简历采集软件 编辑:程序博客网 时间:2024/05/16 14:53

本地图片操作时的优化

车商的有一个发车传照的功能,需要上传本地的照片到服务器,上传之前需要对照片做是否横向拍摄的拍摄的检测,以前一直写法(见以下代码),只要使用了这句代码BitmapFactory.decodeFile(fileString),图片就被加载到了内存中,如果图片很大,会有一定概率引起java.lang.OutOfMemory异常。

    /**     * 检测照片横竖     *     * @param fileString the image native path     * @return {@code true} if this image is horizontal     */    public static boolean isImgHorizontal(String fileString) {        Bitmap bitmap = BitmapFactory.decodeFile(fileString);        boolean temp = bitmap.getWidth() > bitmap.getHeight();        if (bitmap != null) {            bitmap.recycle();            bitmap = null;        }        return temp;    }
如果你不需要使用到图片,只需要获取图片的信息(如高宽类型等),又或者你需要在使用图片前知道图片的大小,再根据自己的需要,压缩成你自己需要的大小,那么建议你这么优化
/**     * 检测照片是否横向     *     * @param imgPath the image path     * @return {@code true} if this image is horizontal     * @throws FileNotFoundException     */    public static boolean isImageHorizontal(String imgPath) throws FileNotFoundException {        if (imgPath == null) {            throw new FileNotFoundException("image file null @method isImageHorizontal");        }        File file = new File(imgPath);        if (file == null || !file.exists()) {            throw new FileNotFoundException("image file not found @method isImageHorizontal");        }        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true; //allowing the caller to query the bitmap without having to allocate the memory for its pixels.        BitmapFactory.decodeFile(imgPath, options);        return options.outWidth > options.outHeight;    }

当 options.inJustDecodeBounds = true时,在BitmapFactory.decodeFile时,图片本身不会加载,而只是单单的读取了图片的信息,存在options对象中。

0 0