2012-08-06 170 views
2

我有存储在SD卡上的图像(大小为〜4MB)。Android图像调整大小

我想调整每个,而不是将其设置为ImageView。

但我不能这样做使用BitmapFactory.decodeFile(path) becouse异常
java.lang.OutOfMemoryError出现。

如何在不将内容加载到内存中的情况下调整图像大小。这是真的吗?

+0

看到这个问题:http://stackoverflow.com/questions/10314527/caused-by-java-lang-outofmemoryerror-bitmap-size-exceeds-vm-budget – brthornbury 2012-08-06 15:28:07

回答

4

使用位图选项:

final BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inPreferredConfig = Bitmap.Config.RGB_565; //Use this if you dont require Alpha channel 
options.inSampleSize = 4; // The higher, the smaller the image size and resolution read in 

然后设置选项解码

BitmapFactory.decodeFile(path, options) 

Here is a good link to read through, about how to display Bitmaps effciently.

你甚至可以写出这样的方法在你希望得到一个尺寸图像解析度。

以下方法检查图像的大小,然后从文件中解码,使用样本内大小来相应地调整来自SD卡的图像大小,同时将内存使用量保持在较低水平。

public static Bitmap decodeSampledBitmapFromFile(string path, 
     int reqWidth, int reqHeight) { // BEST QUALITY MATCH 

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

    // Calculate inSampleSize 
     // Raw height and width of image 
     final int height = options.outHeight; 
     final int width = options.outWidth; 
     options.inPreferredConfig = Bitmap.Config.RGB_565; 
     int inSampleSize = 1; 

     if (height > reqHeight) { 
      inSampleSize = Math.round((float)height/(float)reqHeight); 
     } 

     int expectedWidth = width/inSampleSize; 

     if (expectedWidth > reqWidth) { 
      //if(Math.round((float)width/(float)reqWidth) > inSampleSize) // If bigger SampSize.. 
      inSampleSize = Math.round((float)width/(float)reqWidth); 
     } 


    options.inSampleSize = inSampleSize; 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 

     return BitmapFactory.decodeFile(path, options); 
    } 
0

你必须扩展您的Bitmap之前使用它,这样你可以减少内存消耗。

看看this,它可能会帮助你。

而且,确保你recycleBitmap如果你不需要他了。