Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert bitmap to byte array and byte array to bitmap in android?

I convert bitmap to byte array and byte array to bitmap but when I have to show converted byte array in ImageView then it will show image with black corners not show in PNG format. I want to show image in PNG format, how can I do that??

Image display after convert byte array to bitmap

Here is a code for bitmap to byte array conversion and byte array to bitmap:

Bitmap into byte array in PNG compressed format:

public byte[] convertBitmapToByteArray(Bitmap bitmap) {
    ByteArrayOutputStream stream = null;
    try {
        stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

        return stream.toByteArray();
    }finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                Log.e(Helper.class.getSimpleName(), "ByteArrayOutputStream was not closed");
            }
        }
    }
}

and convert byte array to bitmap as:

BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

1 Answers

Try this code

//For encoding toString
public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = android.util.Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}
//For decoding
String str=encodedImage;
byte data[]= android.util.Base64.decode(str, android.util.Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
like image 151
Abhishek Singh Avatar answered Oct 28 '25 19:10

Abhishek Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!