2013-06-18 121 views
7

我這樣旋轉的位圖上,每個按鍵點擊圖片旋轉90度旋轉位圖會導致OutOfMemoryException異常

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

我用大量的圖片想這一點,但現在一個造成OutOfMemoryError異常。有沒有辦法來防止這種情況?當然,我可以打電話回收,但後來我失去了位圖,必須從imageview中重新獲得它。我不認爲這會有所作爲。

+1

可能會有幫助嗎? http://developer.android.com/training/displaying-bitmaps/index.html –

+0

如果旋轉ImageView是一種替代方案,那就去吧! – Carnal

+0

旋轉ImageView不是一個選項,我保存位圖後。儘管在其他情況下,這是一個更好的選擇。 –

回答

13

我有建議給你。

1)如果您有任何記憶飢餓任務,請在方法中使用,如果可能,請使用AsyncTask
2)聲明對象爲WeakReference。這會讓你有機會在使用後釋放內存。看下面的例子。

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

此任務的所有視圖和對象爲WeakReference。完成此任務後,此任務使用的所有內存都是空閒的。嘗試這種方法。我用在我的應用程序中。

+1

這是早上4點的救星。 – Ichthyocentaurs

+0

很高興幫助你.. :) –

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); 
+0

我需要保持PNG格式。不過謝謝。 –

0

如果您只是需要查看圖像時,可以設置一個旋轉抽拉爲shown here

如果你關心的位圖的真正的旋轉,並且還希望爲避免OOM,請檢查this link

相關問題