Android 解决OOM

1,压缩图片时报OOM-compress()

 /**
     * @param context
     * @param srcPath  原图片路径
     * @param savePath 压缩后图片的保存路径
     */
    public static boolean compress(Context context, String srcPath, String savePath) {
        int[] screenSize = Utility.initScreenSize(context);//获取屏幕宽高

        BitmapFactory.Options opts = new BitmapFactory.Options();

        opts.inJustDecodeBounds = true;

        //之前漏掉了这句话,导致size=0,没有压缩率,直接解析的原图。
        BitmapFactory.decodeFile(srcPath, opts);
        int w = opts.outWidth;
        int h = opts.outHeight;

        opts.inJustDecodeBounds = false;

        float a = w / screenSize[0];
        float b = h / screenSize[1];
        //得到最大的压缩率
       int size size = (int) Math.max(a, b);
        opts.inSampleSize = size;

        Bitmap decodeFile = BitmapFactory.decodeFile(srcPath, opts);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int quality = 80;
        //按比例压缩
        decodeFile.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        decodeFile = rotateBitmapByDegree(decodeFile, getBitmapDegree(srcPath));

        //按质量压缩
        while (baos.toByteArray().length > 100 * 1024 && quality > 20) {
            baos.reset();
            quality -= 30;
            decodeFile.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        }

        try {
            baos.writeTo(new FileOutputStream(savePath));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                baos.flush();
                baos.close();
                if (!decodeFile.isRecycled()) {
                    decodeFile.recycle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

参考:http://263229365.iteye.com/blog/1562924

2, 使用Glide框架加载图片时报OOM.

将ImageView的scaleType设置成fitCenter,centerCrop,不要设置为fitXY。
fitXY会强制让Glide读取一个完全分辨率的图片,事实上我们只需要一个缩略图。

参考:http://blog.csdn.net/lijinhua7602/article/details/46495353

你可能感兴趣的:(Android)