24 September 2014

Encode large size image to Base64 String in android

Encode large size  image to Base64 String in android



In here i have described how to encode large size of image to base64 String.For example when you want to upload images to server using android application most of the times image size is (2MB-5MB).So Using normal byte inputstream it is difficult to upload image.It gives out of memory error when encoding image.So that is why we encode image to String using base64 and decode string to Image in server side.

Encode Image


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;

    }

Happy Coding.