安卓|获取和压缩位图的正确方法 |内存不足

标签 android bitmap out-of-memory

在我的应用程序中,我得到一张图片(位图):

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/

相关文章:

java - "Cannot draw recycled bitmaps"如果我在 onDestroy() 中调用 recycle()

android - 如何在 Mac 中以 root 用户身份从命令行运行 Android Studio 3.0

android - 从字符串路径创建位图

java - 动态改变imageView中的位图,android

kubernetes - 为什么kubernetes OOM会杀死一个暂停容器?

java - HashMap 和 ArrayList 的 Android OutOfMemoryError

android - 从子 Activity 中获取主要 Activity 的推荐方法是什么

Android 捕获照片 putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));数据为空

java - 从 Stripe Android 中删除用户卡

android - 在我用大量数据发出大量请求后,Volley 给我内存不足异常