安卓将来自相册的图像转换为base64时导致内存溢出异常

3

我希望能够从相册中加载图像,然后将其转换为base64编码。

这听起来并不困难。所以我是这样做的:

首先打开相册并选择图片:

picteureBtn.setOnClickListener(new View.OnClickListener() {
            private Uri imageUri;

            public void onClick(View view) {
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);

            }
        });

第二个onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();


        }


    }

最后一步,我想要解码我的图片,它位于picturePath

                String b64;
                StringEntity se;
                String entityContents="";
                if (!picturePath.equals("")){
                    Bitmap bm = BitmapFactory.decodeFile(picturePath);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                    byte[] b = baos.toByteArray(); 
                    b64=Base64.encodeToString(b, Base64.DEFAULT);
                }

很遗憾我得到了以下错误信息:
06-24 16:38:14.296: E/AndroidRuntime(3538): FATAL EXCEPTION: main
06-24 16:38:14.296: E/AndroidRuntime(3538): java.lang.OutOfMemoryError
06-24 16:38:14.296: E/AndroidRuntime(3538):     at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)

有人能指出我错在哪里吗?

2个回答

5
我建议更改为:

我建议进行更改


Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//added lines
bm.recycle();
bm = null;   
//added lines 
byte[] b = baos.toByteArray(); 
b64=Base64.encodeToString(b, Base64.DEFAULT);

那样做可以避免将Bitmap两次加载到应用程序的内存中。

4

有很多文章谈论这个问题,基本上在尝试将其解码为Bitmap之前,您需要计算出其尺寸,请查看BitmapFactory类。我有一个替代方案,因为您正在从图库中选择图片,所以可以在activityForResult中获取Bitmap,像这样:

Bitmap image = (Bitmap) data.getExtras().get("data");

您可以通过以下方式开始获取图片的Intent

Intent intent = new Intent();    
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT); 
startActivityForResult(intent, RESULT_LOAD_IMAGE);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接