代码参考:
/**
* 根据View(主要是ImageView)的宽和高来获取图片的缩略图
* @param path
* @param viewWidth
* @param viewHeight
* @return
*/
private Bitmap decodeThumbBitmapForFile(String path, int viewWidth, int viewHeight){
BitmapFactory.Options options = new BitmapFactory.Options();
//设置为true,表示解析Bitmap对象,该对象不占内存
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
//设置缩放比例
options.inSampleSize = computeScale(options, viewWidth, viewHeight);
//设置为false,解析Bitmap对象加入到内存中
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
/**
* 根据View(主要是ImageView)的宽和高来计算Bitmap缩放比例。默认不缩放
* @param options
* @param width
* @param height
*/
private int computeScale(BitmapFactory.Options options, int viewWidth, int viewHeight){
int inSampleSize = 1;
if(viewWidth == 0 || viewHeight == 0){
return inSampleSize;
}
int bitmapWidth = options.outWidth;
int bitmapHeight = options.outHeight;
//假如Bitmap的宽度或高度大于我们设定图片的View的宽高,则计算缩放比例
if(bitmapWidth > viewWidth || bitmapHeight > viewWidth){
int widthScale = Math.round((float) bitmapWidth / (float) viewWidth);
int heightScale = Math.round((float) bitmapHeight / (float) viewWidth);
//为了保证图片不缩放变形,我们取宽高比例最小的那个
inSampleSize = widthScale < heightScale ? widthScale : heightScale;
}
return inSampleSize;
}
另外可参照:
BitmapFactory.Options options = new BitmapFactory.Options();
/**
* 最关键在此,把options.inJustDecodeBounds = true;
* 这里再decodeFile(),返回的bitmap为空,但此时调用options.outHeight时,已经包含了图片的高了
*/
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/test.jpg", options); // 此时返回的bitmap为null
/**
*options.outHeight为原始图片的高
*/
Log.e("Test", "Bitmap Height == " + options.outHeight);
根据这些方法,可以在实际加载Bitmap图片之前根据需要设置图片缩小为原来的(1/2,1/4,1/8,1/16..)
下面是Android源码中关于 inSampleSize的说明:
<span style="background-color: rgb(51, 255, 51);">public int inSampleSize</span>
Added in API level 1
If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2,<span style="background-color: rgb(51, 255, 51);"> any other value will be rounded down to the nearest power of 2</span>.