我正在尝试将我的图像缩小到较小的尺寸,我将它们加载到imageview中,然后我开始获得“位图大小超过VM预算”的异常。另一方面,如果我得到缩略图而不是实际图像并显示它们运行平稳。但我需要实际图像的URI供以后使用,如果我马上加载缩略图,我就无法获得。
环顾四周后,我发现了一种方法,但它没有用。
代码:
Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, name);
uriList.add(uri.getPath());
File image = new File(uri.getPath());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap actualBitmap = BitmapFactory.decodeFile(image.getPath(), options);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(actualBitmap, image_width, image_height, false);
iv.setImageBitmap(scaledBitmap);
我获得actualBitmap的部分返回null,因此imageview为空。如果我打印uri.getpath()
,它会给出:
/external/images/media//sdcard/dcim/Camera/imagename.jpg
我的问题是,这是正确的做法吗?如果是的话,我做错了什么,如果不是,请有人指出我正确的方向。
答案 0 :(得分:2)
尝试使用以下代码
public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,
int targetHeight) {
Bitmap bitMapImage = null;
// First, get the dimensions of the image
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
double sampleSize = 0;
// Only scale if we need to
// (16384 buffer for img processing)
Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
.abs(options.outWidth - targetWidth);
if (options.outHeight * options.outWidth * 2 >= 1638) {
// Load, scaling to smallest power of 2 that'll get it <= desired
// dimensions
sampleSize = scaleByHeight ? options.outHeight / targetHeight
: options.outWidth / targetWidth;
sampleSize = (int) Math.pow(2d,
Math.floor(Math.log(sampleSize) / Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[128];
while (true) {
try {
options.inSampleSize = (int) sampleSize;
bitMapImage = BitmapFactory.decodeFile(filePath, options);
break;
} catch (Exception ex) {
try {
sampleSize = sampleSize * 2;
} catch (Exception ex1) {
}
}
}
return bitMapImage;
}