2011-09-27 79 views
1

在我需要上傳圖像的服務器上有2MB限制。上傳前下載圖像大小限制下限

我使用此方法來下采樣位圖Strange out of memory issue while loading an image to a Bitmap object

此方法

public InputStream getPhotoStream(int imageSizeBytes) throws IOException { 
     int targetLength = 1500; 
     ByteArrayOutputStream photoStream; 
     byte[] photo; 
     Bitmap pic; 
     final int MAX_QUALITY = 100; 
     int actualSize = -1; 
     do { 
      photo = null; 
      pic = null; 
      photoStream = null; 

      //this calls the downsampling method 
      pic = getPhoto(targetLength); 

      photoStream = new ByteArrayOutputStream(); 
      pic.compress(CompressFormat.JPEG, MAX_QUALITY, photoStream); 
      photo = photoStream.toByteArray(); 
      actualSize = photo.length; 
      targetLength /= 2; 
     } while (actualSize > imageSizeBytes); 
     return new ByteArrayInputStream(photo); 
} 

這將引發的OutOfMemoryError在第二次迭代內。我怎樣才能將圖像縮小到一定的大小限制以下?

+0

試試這個。 http://blog.androidquery.com/2011/05/down-sample-images-to-avoid-out-of.html –

回答

1

我認爲問題在發生,因爲您正在將圖像壓縮到內存表示中,您需要在嘗試再次壓縮之前釋放該內存。

您需要在photoStream中調用close()才能再次嘗試釋放資源。 也toByteArray()複製內存中的流,你必須稍後釋放,爲什麼不使用photoStream.size()來檢查文件大小?

如果需要,我可以發佈一些代碼。

+0

謝謝,不幸的是,我仍然失去記憶錯誤 – siamii

1

取而代之的是:

pic = null; 

這樣做:

if (pic!=null) 
    pic.recycle(); 
pic = null 

如果簡單地將位圖對象爲null它所佔用不立即釋放內存。在第二種情況下,您明確告訴操作系統您已完成位圖並可以釋放其內存。

另外考慮使用90而不是100的壓縮質量,我相信會相應地減少產生的文件大小。

+0

謝謝,不幸的是我仍然有內存錯誤 – siamii