Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android resizing large image recieved as base64 string

i have some issue resizing an image in android. i have a base64 string (i don't have a file or a url, just the string) and so far i get a out of memory exception as soon as i try to decode it.

public String resizeBase64Image(String base64image){

    byte [] encodeByte=Base64.decode(base64image,Base64.DEFAULT); //out of memory exception...

    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inPurgeable = true;
    Bitmap image = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length,options);

    image = Bitmap.createScaledBitmap(image, IMG_WIDTH, IMG_HEIGHT, false);

    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] newbytes=baos.toByteArray();

    return Base64.encodeToString(newbytes, Base64.DEFAULT);

}

Does anybody have an idea?

like image 331
George Avatar asked Jul 04 '26 17:07

George


1 Answers

it took me a while to come back to this project but i finally found a solution to my issue. first, i needed to modify the application tag of the Manfest to add largeHeap=:true":

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:largeHeap="true" >

Making use of the garbage collector helped a lot.

public String resizeBase64Image(String base64image){
    byte [] encodeByte=Base64.decode(base64image.getBytes(),Base64.DEFAULT); 
    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inPurgeable = true;
    Bitmap image = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length,options);


    if(image.getHeight() <= 400 && image.getWidth() <= 400){
        return base64image;
    }
    image = Bitmap.createScaledBitmap(image, IMG_WIDTH, IMG_HEIGHT, false);

    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG,100, baos);

    byte [] b=baos.toByteArray();
    System.gc();
    return Base64.encodeToString(b, Base64.NO_WRAP);

}   
like image 101
George Avatar answered Jul 07 '26 07:07

George