【问题标题】:How to convert bitmap to byte array and byte array to bitmap in android?如何在android中将位图转换为字节数组并将字节数组转换为位图?
【发布时间】:2018-05-06 00:24:52
【问题描述】:

我将位图转换为字节数组,将字节数组转换为位图,但是当我必须在 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 空格的图像

标签: java android arrays bitmap


【解决方案1】:

试试这个代码

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

【讨论】:

    【解决方案2】:

    使用此代码:

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

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 2023-04-06
      • 1970-01-01
      • 2010-09-26
      • 2013-01-14
      • 2013-07-29
      • 2011-06-26
      相关资源
      最近更新 更多