Adir Rahamim
Adir Rahamim

Reputation: 453

Images load from sdcard

i download about 100 pictures from my server inorder to show them in a listView,

therefore i save them in my sdcard that i will not receive a OutOfMemoryException.

however, i see that even if i download them to the sdcard, i must decode them to a Bitmap which takes alot of memory and then to show them, therefore i also get a "OutOfMemory" Exception.

is there anything to deal with it?

thanks alot

this is my code to load image from sdcard:

Bitmap bmImg = BitmapFactory.decodeFile("path of img1");
imageView.setImageBitmap(bmImg);

Upvotes: 0

Views: 163

Answers (1)

Emil Adz
Emil Adz

Reputation: 41099

Try to use this code for loading the image from file:

 img.setImageBitmap(decodeSampledBitmapFromFile(imagePath, 1000, 700));

when decodeSampledBitmapFromFile:

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);
  }

you can play with the number (1000, 700 in this case) to configure what quality the output of the image file would be.

Upvotes: 2

Related Questions