Android将图像从库转换为base64导致OutOfMemory异常

Mit*_*d1r 2 java memory android

我想从库加载图像,然后将其转换为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);

            }
        });
Run Code Online (Sandbox Code Playgroud)

第二个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();


        }


    }
Run Code Online (Sandbox Code Playgroud)

并且为了最终的方式我想解码我的image那个picutrePath

                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);
                }
Run Code Online (Sandbox Code Playgroud)

不幸的是我得到了:

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)
Run Code Online (Sandbox Code Playgroud)

任何人都可以指出我在哪里做错了吗?

Dig*_*ara 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);
Run Code Online (Sandbox Code Playgroud)

这样,您就不会将Bitmap两次加载到应用程序的内存中.