2013-06-04 276 views
2

我減少圖像的大小使用此項功能:減少BitmapDrawable大小

Drawable reduceImageSize (String path) 
{ 
    BitmapDrawable bit1 = (BitmapDrawable) Drawable.createFromPath(path); 
    Bitmap bit2 = Bitmap.createScaledBitmap(bit1.getBitmap(), 640, 360, true); 
    BitmapDrawable bit3 = new BitmapDrawable(getResources(),bit2); 
    return bit3; 
} 

而且其做工精細,唯一的問題是,當我打電話的應用越來越慢這個功能多的時候,有沒有什麼辦法優化這個功能?也許通過矩陣縮小大小? 此外,我正在讀取SD卡中的圖像,並且需要背部作爲可繪製的動畫,並且此功能提供了此功能。

回答

4

使用BitmapFactory.OptionsinJustDecodeBounds規模下來:

Bitmap bitmap = getBitmapFromFile(path, width, height);

public static Bitmap getBitmapFromFile(String path, int width, int height) { 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, width, height); 

    options.inJustDecodeBounds = false; 
    Bitmap bitmap = BitmapFactory.decodeFile(path, options); 
    return bitmap; 
} 

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) { 
     if (width > height) { 
      inSampleSize = Math.round((float)height/(float)reqHeight); 
     } else { 
      inSampleSize = Math.round((float)width/(float)reqWidth); 
     } 
    } 
    return inSampleSize; 
} 

瞭解更多關於在這裏:​​Loading Large Bitmaps Efficiently

而且,我不知道你在哪裏調用此方法,但如果你有很多人,請確保你使用LruCache或類似的緩存位圖:Caching Bitmaps