OutOfMemoryError with image selection in Android. How to resize image before decoding it to bitmap?

后端 未结 5 1680
深忆病人
深忆病人 2021-01-16 17:52

I\'m building an imagepicker in my Android app, for which I used the example code on this page. This basically gives me a button which opens the possibility to get a file fr

5条回答
  •  渐次进展
    2021-01-16 18:29

    Basically, you should use BitmapFactory.decodeFile(path, options) passing Bitmap.Options.inSampleSize to decode a subsampled version of the original Bitmap.

    Your code will look something like this:

    public Bitmap decodeBitmap(String path, int maxWidth, int maxHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateInSampleSize(maxWidth, maxHeight, options.outWidth, options.outHeight);
        return BitmapFactory.decodeFile(path, options);
    }
    

    And the calculateInSampleSize code:

    private int calculateInSampleSize(int maxWidth, int maxHeight, int width, int height) {
        double widthRatio = (double) width / maxWidth;
        double heightRatio = (double) height / maxHeight;
        double ratio = Math.min(widthRatio, heightRatio);
        float n = 1.0f;
            while ((n * 2) <= ratio) {
                n *= 2;
            }
            return (int) n;
        }
    

提交回复
热议问题