问题描述: 在Android开发中,当将Bitmap转换为字节数组后再将其转回时,颜色可能不正确。
解决方法:
使用Bitmap的compress方法将Bitmap转换为字节数组时,指定格式为Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG,而不是使用默认的Bitmap.CompressFormat.WEBP。
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
在将字节数组转换回Bitmap时,使用BitmapFactory的decodeByteArray方法,并指定Bitmap.Config的格式为ARGB_8888。
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Bitmap convertedBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
完整示例:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
// 将Bitmap转换为字节数组
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// 将字节数组转换回Bitmap
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Bitmap convertedBitmap = decodedBitmap.copy(Bitmap.Config.ARGB_8888, true);
通过以上方法,在将Bitmap转换为字节数组后再转回时,可以确保颜色正确。