1.读取图片信息(宽、高、MimeType)
BitmapFactory.Options options = new BitmapFactory.Options();//options对象用来存放图片的信息
options.inJustDecodeBounds = true;//true表示返回一个为null的Bitmap,这样不占用内存
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);//把图片信息写入options对象
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
当然以下静态方法也是可以获得options对象的
BitmapFactory.decodeFile(String pathName, Options opts);
BitmapFactory.decodeByteArray(byte[] data, int offset, int length, Options opts);
BitmapFactory.decodeStream(InputStream is, Rect outPadding, Options opts);
2.计算缩放大小
为了告诉解码器去加载一个缩小版本的图片到内存中,需要在BitmapFactory.Options 中设置 inSampleSize 的值。例如, 一个分辨率为2048x1536的图片,如果设置 inSampleSize 为4,那么会产出一个大约512x384大小的Bitmap。加载这张缩小的图片仅仅使用大概0.75MB的内存,如果是加载完整尺寸的图片,那么大概需要花费12MB(前提都是Bitmap的配置是 ARGB_8888)。下面有一段根据目标图片大小来计算Sample图片大小的代码示例:
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) {
final int halfHeight = height / 2;
final int 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;
}
}
return inSampleSize;
}
为了使用该方法,首先需要设置 inJustDecodeBounds 为 true
, 把options的值传递过来,然后设置inSampleSize 的值并设置 inJustDecodeBounds 为 false
,之后重新调用相关的解码方法。
3.解码,返回缩小的Bitmap
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
// 第一次设置 inJustDecodeBounds=true 只是计算尺寸
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 计算 inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}