Wai Yan Hein
Wai Yan Hein

Reputation: 14791

Converting bitmap to bytearray to string then convert back to bitmap is always null in Android

I am developing an Android app. In my app, I am working with bitmaps. What I am doing is I am converting bitmap to byte array. Then I convert byte array to string. I need to do it some reasons. Converting bitmap to byte array is working. Byte array to string is also converted. Then problem start when I work with that converted string. I am converting that string back to byte array. Then I convert that byte array back to bitmap. But bitmap is always null.

This is my function that convert bitmap to byte array

public static byte[] ConvertBitmapToByteArray(Bitmap bitmap)
    {
        if(bitmap==null)
        {
            return null;
        }
        else{
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            return byteArray;
        }
}

This is function that converts byte array to bitmap

 public static Bitmap ConvertByteArarysToBitmap(byte[] byteArray)
    {
        if(byteArray!=null)
        {
            return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        }
        else{
            return null;
        }
}

These are the steps I am converting

byte[] byteArray = Helper.ConvertBitmapToByteArray(Bitmap bitmap);
//convert byte array to string
String imageString = new String(byteArray,"UTF-8");
//I convert that string back to byte array
byte[] reconvertedByteArray = imageString.getBytes("UTF-8");
Bitmap reconvertedBitmap = Helper.ConvertByteArarysToBitmap(reconvertedByteArray);

In my code, the last reconvertedBitmap is always null. What is wrong with my code? What is the correct way to convert byte array to string and then convert back that string to byte array. What is missing in my code?

Upvotes: 0

Views: 1060

Answers (1)

Dan Harms
Dan Harms

Reputation: 4840

To properly convert a byte[] to a String, you should use Base64.encodeToString().

Documentation

Upvotes: 2

Related Questions