3

In my application I have faced a small issue in encoding and decoding images to String and pass it to web service. After getting the bitmap image, I convert it into byte[] and encode to String value but in Some cases it shows error I don't know why it comes. And one more doubt is Base64 class only supports to convert Bitmap image to String or any other tools available to do the same.

Thanks in advance...

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Srinivasan
  • 4,481
  • 3
  • 28
  • 36
  • It shows like Out of Memory Exception i thought the String will not hold that much big String value is that true... – Srinivasan Jul 24 '12 at 08:56

2 Answers2

12

In the case of OutOfMemoryError, below code helps me.

public String BitMapToString(Bitmap bitmap){
        ByteArrayOutputStream baos=new  ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100, baos);
        byte [] b=baos.toByteArray();
        String temp=null;
        try{
        System.gc();
        temp=Base64.encodeToString(b, Base64.DEFAULT);
        }catch(Exception e){
            e.printStackTrace();
        }catch(OutOfMemoryError e){
            baos=new  ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,50, baos);
            b=baos.toByteArray();
            temp=Base64.encodeToString(b, Base64.DEFAULT);
            Log.e("EWN", "Out of memory error catched");
        }
        return temp;
  }

Basically what i did is : i catch OutofMemoryError and in that catch block i resize it by 50% and then i encode it to string.

rajpara
  • 5,203
  • 1
  • 29
  • 46
  • @Sri right dude , it will resize the image because i have to encode large image(around 3-5 mb) and need to sent to server. – rajpara Jul 24 '12 at 09:13
2

Try My Below Sample Code Of Project

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

        img.setImageBitmap(bmp);
        btnadd.requestFocus();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

        byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
        Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                bytarray.length);
Yash
  • 1,751
  • 13
  • 14