2017-02-17 20 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