Frink
Frink

Reputation: 221

Large images to base64

I search for this over forum but I not find good solution. I found very similar themes, but not helping.

I have problem when i try to encode large image files to base64.. I try to use lower quality but i have problem with large files again.. i use :

public String BitMapToString(Bitmap bitmap,String Ext){
    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    if(Ext.equals("png")){
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos); 
    }else{
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, 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();
            if (Ext.equals("png")) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 20, baos); 
            } else {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);   
            }
            b = baos.toByteArray();
            temp = Base64.encodeToString(b, Base64.DEFAULT);
            Log.e("EWN", "Out of memory error catched");
        }
        return temp;        
}

Now this work for litle files excelent ( lets say <1 mb) when i use quality lower than 100 (in this example 50 or 20) i get ok with litle large file(maybe 3 mb ) but this is not good solution because i still have problem with size 10 mb for example...Program just break..

I was think to convert in chunks ,but this not work for me...

Thank you for answer.

Upvotes: 0

Views: 3891

Answers (1)

Damian Nikodem
Damian Nikodem

Reputation: 1289

well the first question would be is there an alternative to base64 encoding the image, what are you using it for? are you then uploading it somewhere or putting it into a database?

does it need to be stored as a string ? Loading such a large image is dangerous, I would personally deal with it using streams instead of loading the entire thing directly.

Apache commons has a commons-codec library which is availible here: http://commons.apache.org/proper/commons-codec/

and it should be simple enough to port:

org.apache.commons.codec.binary.Base64OutputStream and org.apache.commons.codec.binary.Base64InputStream

into your app. This should allow you to first dump your data in chunks to disk and then read in smaller blocks as you use it for whatever purpose you need to.

Upvotes: 1

Related Questions