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

3

我将位图转换为字节数组,也将字节数组转换为位图,但当我要在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");
            }
        }
    }
}

将字节数组转换为位图,代码如下:

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

@Prem,这不显示PNG格式的图像。显示带有黑色PNG空间的图像。 - user5269722
2个回答

10

尝试一下这段代码

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

0
请使用以下代码:
public String convertBitmapToString(Bitmap bmp){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream); //compress to which format you want.
        byte[] byte_arr = stream.toByteArray();
        String imageStr = Base64.encodeBytes(byte_arr);
        return imageStr;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接