3

I'm trying to encode an image to 64 base ,

after choosing the image from gallery and trying to save it I am getting this error:

outOfMemory Exception

can any one suggest how to to get this image to base 64 without memory error?

        MotorImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
}


 @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]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();


 //   
   ImageView imageView = (ImageView) findViewById(R.id.imageView1);
    imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));



    String imageString = null;

    try {
        Bitmap bm = BitmapFactory.decodeFile(picturePath);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object  
        bm.recycle();
        byte[] b = baos.toByteArray();
        imageString = Base64.encodeToString(b, Base64.DEFAULT);
    } catch (Exception e) {
        e.printStackTrace();
    }




    Toast.makeText(getApplicationContext(), imageString, Toast.LENGTH_SHORT).show();
6
  • Do not write to ByteArrayOutputStream, write to a file, network socket, ... you can't write arbitrarily large data into memory. Also don't encode to String because that's writing into memory as well. There are outputstreams for that as well. Commented Jan 30, 2014 at 17:28
  • i want to save it as string cuz i will store it in sql server database , what should i use ? Commented Jan 30, 2014 at 17:30
  • You don't need a String, you can stream it to your server as well. How depends on your server and many other factors. Commented Jan 30, 2014 at 17:37
  • base64-ing an image is really not a good idea and should be avoided. Commented Jan 30, 2014 at 17:50
  • 1
    use Base64OutputStream on a file. Commented Jan 30, 2014 at 18:08

3 Answers 3

2

I suspect you need to scale and resample your image to fit within the constraints on the device, try something like this

// decodes image and scales it to reduce memory consumption
private Bitmap decodeImage(String picturePath) {
    try {
        File file = new File(picturePath);
        // Get image size
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(file), null, opts);

        // The new size we want to scale to
        final int MIN_SIZE = 70;

        // Find the correct scale value.
        int scale = 1;
        while (((opts.outWidth / scale) >> 1) >= MIN_SIZE
                && ((opts.outHeight / scale) >> 1) >= MIN_SIZE) {
            scale <<= 1;
        }

        BitmapFactory.Options opts2 = new BitmapFactory.Options();
        opts2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(file), null, opts2);
    } catch (FileNotFoundException e) {
    }
    return null;
}
Sign up to request clarification or add additional context in comments.

5 Comments

can you edit this with taking string of image path instead of File
@user3245658 Sorry. I missed that. It's opts. Edited.
@user3245658 I know. But first you must decode it and scale it, then encode it! :)
so I should use my original post here after your method ?
@user3245658 After you scale the image your original method should work; I would suggest you try a streaming solution (instead of an in memory one) for saving; but this should reduce the size of the output enough for it to work.
0

Try to use android:largeHeap="true" inside the application tag on AndroidManifest, then your app will have more ram available and will not throw a oom exception.

1 Comment

what is your android version?
0

If you read the official document of android you will come to know that this is a common issue with android and the recommended solution is to resize image according to your need. you can refer developer.android for this as well

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.