我将一个png图像打开并转换成Bitmap格式,在对其进行一些修改后,以jpg格式保存到磁盘中。但当png图像中存在透明区域时,它们会被保存为黑色。是否有方法可以更改此默认行为,使图像保存为不同颜色的背景,例如白色?
谢谢。
我将一个png图像打开并转换成Bitmap格式,在对其进行一些修改后,以jpg格式保存到磁盘中。但当png图像中存在透明区域时,它们会被保存为黑色。是否有方法可以更改此默认行为,使图像保存为不同颜色的背景,例如白色?
谢谢。
你可以将它绘制到一个新的位图上,例如:
Bitmap newBitmap = Bitmap.createBitmap(image.getWidth(),
image.getHeight(), image.getConfig());
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(image, 0F, 0F, null);
然后保存新的位图。
setHasAlpha()
的设置为true,这样做就像这样:mBitmap.setHasAlpha(true);
当保存时,请使用您正在使用的任何保存方法将图像保存为PNG格式,例如:
File file = new File(folderDir, name);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = new FileOutputStream(file);
mBitmap.setHasAlpha(true);
mBitmap.compress(Bitmap.CompressFormat.PNG, 80, out);
out.flush();
out.close();
对于 Kotlin,您可以使用此扩展函数
/**
* Returns a new Bitmap with provided background color and recycles the current one.
*/
fun Bitmap.changeBackgroundColor(color: Int): Bitmap {
val newBitmap = Bitmap.createBitmap(width, height, config)
val canvas = Canvas(newBitmap)
canvas.drawColor(color)
canvas.drawBitmap(this, 0F, 0F, null)
recycle()
return newBitmap
}