16

As the title implies, I'm trying to get the user of my Android app to select an image from his device (done), I then want to scale the image down (done), compress/convert the image to png and send it to an API as a base64 string.

So I currently resize the image like so:

options.inSampleSize = calculateInSampleSize(options, MAX_IMAGE_DIMENSION, MAX_IMAGE_DIMENSION);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);

I then have a bitmap, which I want to convert to a PNG, and from there to a base64. I found some example code to convert to a PNG and store it on the device here.

try {
       FileOutputStream out = new FileOutputStream(filename);
       bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
       out.close();
} catch (Exception e) {
       e.printStackTrace();
}

The problem is that I do not want to save the image. I just want to keep it in memory as a PNG and then convert it further to a base64 string.

Does anybody know how I could convert the image to a png and store it in a variable that way, or even better, convert it to base64 immediately? All tips are welcome!

Community
  • 1
  • 1
kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

40

Try this to convert bitmap into png:

 bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);

Check method's documentation.

You can directly convert bitmap to Base64. Use this for encoding and decoding from and to Base64.

public static String encodeToBase64(Bitmap image)
{
    Bitmap immagex=image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    Log.e("LOOK", imageEncoded);
    return imageEncoded;
}

public static Bitmap decodeBase64(String input) 
{
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
}
Mario Kutlev
  • 4,897
  • 7
  • 44
  • 62
nitesh goel
  • 6,338
  • 2
  • 29
  • 38