簡體   English   中英

如何在android中將位圖轉換為字節數組並將字節數組轉換為位圖?

[英]How to convert bitmap to byte array and byte array to bitmap in android?

我將位圖轉換為字節數組,將字節數組轉換為位圖,但是當我必須在 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);

試試這個代碼

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

使用此代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM