我正在尝试实现对图像进行大量操作的应用程序。我有优化问题。运行我的应用程序的时间太长。我需要压缩我正在处理的图像。我正在尝试使用本教程:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
当我想从drawable文件夹中获取图像时,它很有效。问题是当我想从相机或画廊拍摄照片时。我不知道应该把什么放在“R.id.myimage
”
所以问题是,如何使用这行代码:
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
当我想使用相机或图库而不是可绘制文件夹时?
答案 0 :(得分:0)
要避免OOM错误,请使用以下方法缩放图像
//For resource
image.setImageBitmap(decodeSampledBitmapFromResource("android.resource://com.my.package/drawable/image_name"));
//For file
image.setImageBitmap(decodeSampledBitmapFromResource(filepath));
采样功能:
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 2;
if (height >= reqHeight || width >= reqWidth) {
inSampleSize *= 2;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String file,
int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}