简体   繁体   中英

Decrease the quality of image . OutOfMemory Exception - Android

I am trying to implement the application which is doing lots of operations on an image. I have the problem with optimalization. The time of running my application is too long. I need to compress the images that I'm processing. I was trying with this tutorial:

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

It works well when I want to take the image from drawable folder. The problem is when I want to take the picture from camera or gallery. I have no idea what should I put in " R.id.myimage "

So the question is, how to use this line of code:

BitmapFactory.decodeResource(getResources(), R.id.myimage, options);

when I want to use the camera or gallery instead of drawable folder ?

To avoid OOM error, scale image using:

//For resource
image.setImageBitmap(decodeSampledBitmapFromResource("android.resource://com.my.package/drawable/image_name"));
//For file
image.setImageBitmap(decodeSampledBitmapFromResource(filepath));

Sampling function:

public static int calculateInSampleSize(BitmapFactory.Options options,
    int reqWidth, int reqHeight) {

final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 2;
if (height >= reqHeight || width >= reqWidth) {
    inSampleSize *= 2;
}
return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(String file,
    int reqWidth, int reqHeight) {

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
        reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM