2

I have images stored on sd card(size of each ~ 4MB).

I want to resize each, than set it to ImageView.

But I cannot do it using BitmapFactory.decodeFile(path) becouse Exception
java.lang.OutOfMemoryError is appeared.

How can i resize image without loading it in the memory. Is it real?

MAC
  • 15,799
  • 8
  • 54
  • 95
abilash
  • 897
  • 3
  • 12
  • 32
  • See this question: http://stackoverflow.com/questions/10314527/caused-by-java-lang-outofmemoryerror-bitmap-size-exceeds-vm-budget – brthornbury Aug 06 '12 at 15:28

2 Answers2

4

Use bitmap options:

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565; //Use this if you dont require Alpha channel
options.inSampleSize = 4; // The higher, the smaller the image size and resolution read in

Then set the options in the decode

BitmapFactory.decodeFile(path, options)

Here is a good link to read through, about how to display Bitmaps effciently.

You could even write a method like this to obtain a sized image at your desired resolution.

The following method checks the size the image, then decodes from file, with in-sample size to resize your image from sdcard accordingly, while keeping memory usage at a low.

   public static Bitmap decodeSampledBitmapFromFile(string path,
        int reqWidth, int reqHeight) { // BEST QUALITY MATCH

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
        // Raw height and width of image
        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) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }


    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
  }
IAmGroot
  • 13,760
  • 18
  • 84
  • 154
0

You have to scale your Bitmap before use it, this way you could reduce memory consumption.

Take a look at this, it might help you.

And, make sure you recycle that Bitmap if you don't need him anymore.

Community
  • 1
  • 1
yugidroid
  • 6,640
  • 2
  • 30
  • 45