I am working in an android application and I am using a bitmap to bind an image to an ImageView. My requirement is to rotate that ImageView and give a border to that ImageView. I have successfully implemented this, but after the application uses this activity two-three times a "force close" error appears saying Bitmap out of VM memory. Please help me to minimize the bitmap memory consumption in my code. And let me know how to modify the code for the same?
final int BORDER_WIDTH = 5;
// Set the border color
final int BORDER_COLOR = Color.WHITE;
Bitmap res = Bitmap.createBitmap(CAPTURE_IMAGE.getWidth() + 2
* BORDER_WIDTH, CAPTURE_IMAGE.getHeight() + 2 * BORDER_WIDTH,
CAPTURE_IMAGE.getConfig());
System.gc();
Canvas canvas = new Canvas(res);
Paint paint = new Paint();
paint.setColor(BORDER_COLOR);
canvas.drawRect(0, 0, res.getWidth(), res.getHeight(), paint);
canvas.drawBitmap(CAPTURE_IMAGE, BORDER_WIDTH, BORDER_WIDTH, paint);
Matrix mat = new Matrix();
// Set the Imageview position
mat.postRotate(355);
bMapRotate = Bitmap.createBitmap(res, 0, 0, res.getWidth(),
res.getHeight(), mat, true);
System.gc();
res.recycle();
res = null;
paint = null;
canvas = null;
mat = null;
// Set the captured bitmap image in the imageview
mShareImageView.setImageBitmap(bMapRotate);
I think you should use shrink function like this
bMapRotate = Bitmap.createBitmap(res, 0, 0, res.getWidth(),
res.getHeight(), mat, true);
Bitmap myBitmap = ShrinkBitmap(bMapRotate , 300, 300);
mShareImageView.setImageBitmap(myBitmap );
private Bitmap ShrinkBitmap(String file, int width, int height) {
// TODO Auto-generated method stub
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
it worked for me and i avoided Bitmap out of VM memory exception
in mainfest file add ---> android:largeHeap:"true"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With