虽然加载大的位图文件,BitmapFactory类提供了几种解码方法(decodeByteArray(),decodeFile(),decodeResource(),等等)。
STEP 1
的inJustDecodeBounds属性设置为true,而解码避免了内存分配,为位图对象返回空但设置outWidth,outHeight和outMimeType。该技术允许您在构建位图之前读取图像数据的尺寸和类型(以及内存分配)。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
要避免java.lang.OutOfMemory异常,请在解码之前检查位图的维数。
STEP 2
告诉解码器子样本图像,加载一个较小的版本到内存中,设置inSampleSize为true你BitmapFactory.Options对象。
例如,分辨率为2048x1536且用inSampleSize为4解码的图像会生成大约512x384的位图。将其加载到内存中时,整个图像使用0.75MB而不是12MB。
这里的计算样本大小值是两个基于目标宽度和高度的功率的方法:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.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;
return BitmapFactory.decodeResource(res, resId, options);
}
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;
}
请仔细阅读本链接了解详情。 http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
更改位图的大小: http://stackoverflow.com/questions/4837715/how-to-resize-a-bitmap-in-android 希望这将有助于。 – Yogendra