如何在Android中将位图转换为字节数组并将字节数组转换为位图?

1 java arrays android bitmap

我将位图转换为字节数组,将字节数组转换为位图,但是当我必须在ImageView中显示转换后的字节数组时,它将显示带有黑角的图像,而没有以PNG格式显示。我想以PNG格式显示图片,该怎么办?

将字节数组转换为位图后的图像显示

这是位图到字节数组转换和字节数组到位图代码:

位图以PNG压缩格式转换为字节数组:

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");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并将字节数组转换为位图为:

BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Run Code Online (Sandbox Code Playgroud)

Abh*_*ngh 6

试试这个代码

//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);
Run Code Online (Sandbox Code Playgroud)