How to convert bitmap to PNG and then to base64 in Android?

Viewed 24187

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!

1 Answers
Related