爲了節省內存,不少狀況下原圖片都要通過縮放處理,根據控件的尺寸來處理成對應尺寸的圖片,這時使用BitmapFactory建立Bitmap,不少狀況下都會使用下面的代碼: 程序員
1
2
3
4
5
6
|
BitmapFactory.Options options =newBitmapFactory.Options();
options.inJustDecodeBounds =true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
intimageHeight = options.outHeight;
intimageWidth = options.outWidth;
String imageType = options.outMimeType;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
publicstaticintcalculateInSampleSize(
BitmapFactory.Options options,intreqWidth,intreqHeight){
// Raw height and width of image
finalint height = options.outHeight;
finalint width = options.outWidth;
intinSampleSize =1;
if(height > reqHeight || width > reqWidth){
finalint halfHeight = height /2;
finalint halfWidth = width /2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while((halfHeight / inSampleSize)> reqHeight
&&(halfWidth / inSampleSize)> reqWidth){
inSampleSize *=2;
}
}
returninSampleSize;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
publicstaticBitmap decodeSampledBitmapFromResource(Resources res,intresId,
intreqWidth,intreqHeight){
// First decode with inJustDecodeBounds=true to check dimensions
finalBitmapFactory.Options options =newBitmapFactory.Options();
options.inJustDecodeBounds =true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds =false;
returnBitmapFactory.decodeResource(res, resId, options);
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
/**
* 對圖片進行壓縮,主要是爲了解決控件顯示過大圖片佔用內存形成OOM問題,通常壓縮後的圖片大小應該和用來展現它的控件大小相近.
*
*
@param context 上下文
*
@param resId 圖片資源Id
*
@param reqWidth 指望壓縮的寬度
*
@param reqHeight 指望壓縮的高度
*
@return 壓縮後的圖片
*/
publicstaticBitmap compressBitmapFromResourse(Context context,intresId,intreqWidth,intreqHeight) {
finalBitmapFactory.Options options =newBitmapFactory.Options();
/*
* 第一次解析時,inJustDecodeBounds設置爲true,
* 禁止爲bitmap分配內存,雖然bitmap返回值爲空,但能夠獲取圖片大小
*/
options.inJustDecodeBounds =true;
BitmapFactory.decodeResource(context.getResources(), resId, options);
finalintheight = options.outHeight;
finalintwidth = options.outWidth;
intinSampleSize =1;
if(height > reqHeight || width > reqWidth) {
finalintheightRatio = Math.round((float) height / (float) reqHeight);
finalintwidthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
options.inSampleSize = inSampleSize;
// 使用計算獲得的inSampleSize值再次解析圖片
options.inJustDecodeBounds =false;
returnBitmapFactory.decodeResource(context.getResources(), resId, options);
}
|