Reputation: 372
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?
Upvotes: 3
Views: 14177
Reputation: 372
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);
}
Upvotes: 12
Reputation: 21766
In the case of OutOfMemoryError, below code may be helpful.
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.
Upvotes: 0