Decode a part of Bitmap from file in Android

后端 未结 6 1364
广开言路
广开言路 2020-12-17 01:40

I have a file with a very large image: for example 9000x9000.

I can\'t load the Bitmap in memory because the heap size. But I only need to display a small part of th

6条回答
  •  醉酒成梦
    2020-12-17 02:25

    Try this code:

    public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
    
            final int height = options.outHeight;
            final int width = options.outWidth;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            int inSampleSize = 1;
            if (height > reqHeight) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            }
            int expectedWidth = width / inSampleSize;
            if (expectedWidth > reqWidth) {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
            options.inSampleSize = inSampleSize;
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(path, options);
        }
    

提交回复
热议问题