2015-11-03 46 views
0

我有一組圖像文件存儲在內部存儲器中,每個文件大小約爲750 KB。我需要用這個圖像創建一個360度的動畫,因此,我將每個圖像加載到一個列表中,而我正在執行此過程時,會出現內存不足異常。 我一直在閱讀關於Android上的位圖處理,但在這種情況下不是關於調整位圖尺寸的大小,因爲它的平板應用程序的尺寸是可以的(600,450),我認爲是關於圖像質量的。 有沒有辦法減少每個位圖佔用的內存?如何讓位圖在Android上佔用更少的內存?

+0

如果圖像需要是600x450位圖,則無法縮小文件大小。 –

+0

好吧,所以我認爲我必須在應用程序中使用它們之前優化圖像。謝謝。 –

回答

0

如果不縮小圖像尺寸,這是不可能的。

所有具有相同尺寸的圖像都需要相同數量的RAM,而不管磁盤大小和壓縮量如何。圖形適配器不理解不同的圖像類型和壓縮,它只需要未壓縮的原始像素數組。它的大小是不變的

例如

size = width * height * 4; // for RGBA_8888

size = width * height * 2; // for RGB_565

所以,你應該減少圖像尺寸或磁盤上使用緩存並從內存中當前看不見的位圖和重裝磁盤需要時。

0

有關於如何做到這一點這裏巨大的資源: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

基本上你需要使用這兩個函數以不同的分辨率加載位圖:

public static int calculateInSampleSize(
     BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     final int halfHeight = height/2; 
     final int halfWidth = width/2; 

     // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
     // height and width larger than the requested height and width. 
     while ((halfHeight/inSampleSize) > reqHeight 
       && (halfWidth/inSampleSize) > reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 

    return inSampleSize; 
} 

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, 
                int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeResource(res, resId, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeResource(res, resId, options); 
} 

然後將圖像作爲如下:

imageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), 
    R.drawable.my_image_resource, 
    imageView.getWidth(), 
    imageView.getHeight())); 

希望有所幫助!

+0

我已經閱讀過這個話題,問題不在於減少圖片尺寸,我只是想知道是否可以降低圖片質量。謝謝你的幫助。 –