Android OutOfMemoryError for large images

后端 未结 3 1379
迷失自我
迷失自我 2021-01-25 05:39

The method throws OutOfMemoryError for large images in size( not by resolution) i have 12 MP photos, all of them are different in size(1.5MB, 2.5MB, 3.2MB, 4.1MB) etc and the re

3条回答
  •  盖世英雄少女心
    2021-01-25 05:56

    Read Article

    Image Size : 4000*3000 in px

    When the image load : 4000*3000*4 = ? KB

    So,Vitrual Heap Memory of the Android device are : 32 MB, 64 MB , 128 MB ... so on

    if you using:

    
    
    
    

    This will increase the VHM double (if 32 MB = 2* 32 MB). BUt this will not an good way to do this, effect on OS

    You need to decrease the size of the image.


    Use the below class and pass the path of the image and width , height what you want

    Bitmap bitmap = BitmapSize.getDecodedBitmap(path, 400, 400);

    Class::::

    public class BitmapSize{
    
    
    
    public static Bitmap getDecodedBitmap(String path, float target_width, float target_height) {
        Bitmap outBitmap = null;
        try {
            Options decode_options = new Options();
            decode_options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path,decode_options);  //This will just fill the output parameters
            int inSampleSize = calculateInSampleSize(decode_options, target_width, target_height);
    
            Options outOptions = new Options();
            outOptions.inJustDecodeBounds = false;
            outOptions.inSampleSize = inSampleSize;
            outOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
            outOptions.inScaled = false;
    
            Bitmap decodedBitmap = BitmapFactory.decodeFile(path,outOptions);
            outBitmap = Bitmap.createScaledBitmap(decodedBitmap,// (int)target_width, (int)target_height, true);
                    (int)((float)decodedBitmap.getWidth() / inSampleSize),
                    (int)((float)decodedBitmap.getHeight() / inSampleSize), true);
            System.out.println("Decoded Bitmap: Width "  + outBitmap.getWidth() + " Height = " + outBitmap.getHeight() + " inSampleSize = " + inSampleSize);
    
        } catch (Exception e) {
            // TODO: handle exception
        }
    
        return outBitmap;
    }
    
    public static int calculateInSampleSize(Options options, float reqWidth, float reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
    
        if (height > reqHeight || width > reqWidth) {
    
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
    
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
    
        return inSampleSize;
    }
    
    }
    

提交回复
热议问题