My code what it does is get an image from the gallery or from the camera and convert this image to base64
, then wait in RealmDB
, when I want to show the image, I convert it from string
to bitmap
and I show it in cardview
with recyclerview
, the detail is that the app
becomes slow and then shows the error and then the application stops.
Also in the android
monitor I see that the memory consumes too much.
Error:
java.lang.OutOfMemoryError: Failed to allocate a 48771084 byte allocation with 16777216 free bytes and 40MB until OOM
Code:
public class ImageDecode {
static String imgDecodableString;
public static String encodeImage(Bitmap bm) {
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();
try{
System.gc();
imgDecodableString= Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
imgDecodableString=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
return imgDecodableString;
}
public static Bitmap decodeBase64(String input) {
byte[] decodedBytes = Base64.decode(input.getBytes(), Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
public static String encodeImages(String path) {
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
try{
System.gc();
imgDecodableString = Base64.encodeToString(b, Base64.DEFAULT);
}catch (OutOfMemoryError e){
baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,50,baos);
imgDecodableString = Base64.encodeToString(b, Base64.DEFAULT);
}
return imgDecodableString;
}
}
This way you show the image:
holder.image.setImageBitmap(ImageDecode.decodeBase64(ProfList.get(position).getImage()));