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

Android | Correct way to get and compress 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