2017-02-17 83 views
3

我有Android位圖縮放和採樣混淆這裏可能有兩個代碼縮放和另一個採樣任何人都可以幫助我確定這兩個代碼的工作和它們之間的主要區別是什麼。
縮放和位圖採樣有什麼區別?

縮放:

public static Bitmap getScaleBitmap(Bitmap bitmap, int newWidth, int newHeight) { 
    int width = bitmap.getWidth(); 
    int height = bitmap.getHeight(); 
    float scaleWidth = ((float) newWidth)/width; 
    float scaleHeight = ((float) newHeight)/height; 

    Matrix matrix = new Matrix(); 
    matrix.postScale(scaleWidth, scaleHeight); 
    return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false); 
} 

採樣:

mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.id.myimage, 100, 100)); 

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

    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeResource(res, resId, options); 

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

    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeResource(res, resId, options); 
} 

public static int calculateInSampleSize(
      BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    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; 

     while ((halfHeight/inSampleSize) >= reqHeight 
       && (halfWidth/inSampleSize) >= reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 

    return inSampleSize; 
} 

這裏既有代碼執行圖像尺寸調整,但不同的方式,使我怎麼能辨別哪一個是好的和簡單。

回答

0

縮放:首先,解碼內存中的整個位圖,然後對其進行縮放。

取樣:您將得到所需的縮放位圖,而不會在內存中加載整個位圖。

0

第一個代碼,需要位圖並創建新的更小的位圖 - 您可以使用memmory作爲更大的位圖。

第二個代碼需要資源。 inJustDecodeBounds使它不會將整個位圖加載到內存中,只是爲它提供信息。然後計算應該如何調整大小,然後再設置inJustDecodeBounds以將虛假加載到內存縮小版本的圖像中。所以你只能使用內存僅用於解碼圖像

Oficial docs