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!
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With