我将位图转换为字节数组,将字节数组转换为位图,但是当我必须在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);
答案 0 :(得分:4)
试试此代码
//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);
答案 1 :(得分: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;
}