Rotating Bitmap Causes Outofmemoryexception
I am rotating a bitmap this way, on every button click the image rotates 90 degrees Matrix matrix = new Matrix(); matrix.postRotate(90); rotated = Bitmap.createBitmap(rotated, 0, 0
Solution 1:
I have suggestions for you.
1) When you have any memory hunger task, use in methods and if possible with AsyncTask.
2) Declare objects as WeakReference. This will give you chance to release memory after use. See below example.
publicclassRotateTaskextendsAsyncTask<Void, Void, Bitmap> {
private WeakReference<ImageView> imgInputView;
private WeakReference<Bitmap> rotateBitmap;
publicRotateTask(ImageView imgInputView){
this.imgInputView = new WeakReference<ImageView>(imgInputView);
}
@Override
protectedvoidonPreExecute() {
//if you want to show progress dialog
}
@Override
protected Bitmap doInBackground(Void... params) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
rotateBitmap = new WeakReference<Bitmap>(Bitmap.createBitmap(rotated, 0, 0,rotated.getWidth(), rotated.getHeight(), matrix, true));
return rotateBitmap.get();
}
@Override
protectedvoidonPostExecute(Bitmap result) {
//dismiss progress dialog
imgInputView.get().setImageBitmap(result);
}
}
This task has all the views and object as WeakReference. When this task is completed, all the memory used by this Task is free. Try this approach. I used in my application.
Solution 2:
Try Like Below:
Matrixmatrix=newMatrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(rotated, 0, 0,rotated.getWidth(), rotated.getHeight(), matrix, true);
ByteArrayOutputStreambmpStream=newByteArrayOutputStream();
rotated.compress(Bitmap.CompressFormat.JPEG,100, bmpStream);
iv.setImageBitmap(rotated);
Solution 3:
If you need to just view the images, you can set a rotate drawable as shown here
If you care about real rotation of the bitmap, and you also want to avoid OOM, check this link
Post a Comment for "Rotating Bitmap Causes Outofmemoryexception"