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

后端 未结 5 1635
深忆病人
深忆病人 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:37

    try this i have used it once . it worked for me.

    private Bitmap getBitmap(String path) {
    
        Uri uri = getImageUri(path);
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = mContentResolver.openInputStream(uri);
    
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();
    
    
    
            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
                  IMAGE_MAX_SIZE) {
               scale++;
            }
            Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", 
               orig-height: " + o.outHeight);
    
            Bitmap b = null;
            in = mContentResolver.openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);
    
                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
                   height: " + height);
    
                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;
    
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, 
                   (int) y, true);
                b.recycle();
                b = scaledBitmap;
    
                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();
    
            Log.d(TAG, "bitmap size - width: " +b.getWidth() + ", height: " + 
               b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(),e);
            return null;
        }
    

提交回复
热议问题