8

我以这种方式旋转位图,在每个按钮上单击图像都会旋转 90 度

Matrix matrix = new Matrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(rotated, 0, 0,
        rotated.getWidth(), rotated.getHeight(), matrix, true);
iv.setImageBitmap(rotated);

我尝试了很多图像,但现在一个导致 OutOfMemoryError。有没有办法防止这种情况?当然我可以调用回收,但是我丢失了位图并且必须从图像视图中再次获取它。我认为这不会有什么不同。

4

3 回答 3

13

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.

public class RotateTask extends AsyncTask<Void, Void, Bitmap> {
    private WeakReference<ImageView> imgInputView;
    private WeakReference<Bitmap> rotateBitmap;

    public RotateTask(ImageView imgInputView){
        this.imgInputView = new WeakReference<ImageView>(imgInputView);
    }

    @Override
    protected void onPreExecute() {
        //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
    protected void onPostExecute(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.

于 2013-06-18T13:11:40.653 回答
0

尝试如下:

Matrix matrix = new Matrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(rotated, 0, 0,rotated.getWidth(), rotated.getHeight(), matrix, true);
ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
rotated.compress(Bitmap.CompressFormat.JPEG,100, bmpStream);
iv.setImageBitmap(rotated);
于 2013-06-18T13:12:32.837 回答
0

如果您只需要查看图像,则可以设置旋转可绘制对象,如下所示

如果您关心位图的实际旋转,并且还想避免 OOM,请查看此链接

于 2014-02-03T12:34:34.320 回答