在我的应用程序中,我得到一张图片(位图):
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select"), GET_CODE);
然后,在 onActivityResult
中,我从 uri 获取位图,其中:
Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri); //here I've the error
对于大图,我得到了错误
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 268435468 byte allocation with 16777216 free bytes and 167MB until OOM
如何正确压缩位图?
最佳答案
正如 CommonsWare 所说,位图已经被压缩了。 你想要原图吗?如果不一定,您可以很容易地调整位图的大小,就像那样:
private static Bitmap decodeBitmap(Context context, Uri theUri, int sampleSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
Log.d(TAG, options.inSampleSize + " sample method bitmap ... "
+ actuallyUsableBitmap.getWidth() + " " + actuallyUsableBitmap.getHeight());
return actuallyUsableBitmap;
}
更多关于 inSampleSize 的信息: http://developer.android.com/intl/es/reference/android/graphics/BitmapFactory.Options.html#inSampleSize
此外,如果您不需要位图的透明度,您可以在选项中将参数 inPreferredConfig 添加到 RGB_565: http://developer.android.com/intl/es/reference/android/graphics/BitmapFactory.Options.html#inPreferredConfig
http://developer.android.com/intl/es/reference/android/graphics/Bitmap.Config.html
关于安卓|获取和压缩位图的正确方法 |内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36583866/