将位图转换为bytearray将其字符串,然后转换回位图在Android中始终为无效



我正在开发一个Android应用程序。在我的应用程序中,我正在使用位图。我正在做的是将位图转换为字节数组。然后,我将字节数组转换为字符串。我需要做一些原因。将位图转换为字节数组正在工作。字节数组到字符串也已转换。然后,当我使用该转换的字符串时,问题开始。我将该字符串转换回字节数组。然后,我将该字节阵列转换回位图。但是位图总是为null。

这是我的功能,将位图转换为字节数组

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;
        }
}

这是将字节数组转换为位图

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

这些是我转换的步骤

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);

在我的代码中,最后一个重新vertertedbitmap始终为null。我的代码怎么了?什么是将字节数组转换为字符串然后将该字符串转换为字节数组的正确方法。我的代码中缺少什么?

要正确将byte[]转换为String,您应该使用Base64.encodeToString()

文档

最新更新