当从png图像创建jpg图像时,将html canvas黑色背景更改为白色背景 [英] Change html canvas black background to white background when creating jpg image from png image
问题描述
我有一个加载了 png
图片的 canvas
。我通过 .toDataURL()
方法得到它的 jpg
base64字符串:
I have a canvas
which is loaded with a png
image. I get its jpg
base64 string by .toDataURL()
method like this:
$('#base64str').val(canvas.toDataURL("image/jpeg"));
但是 png
图片的透明部分在新的 jpg
图片中显示为黑色。
But the transparent parts of the png
image are shown black in the new jpg
image.
任何将此颜色更改为白色的解决方案?
Any solutions to change this color to white? Thanks in advance.
推荐答案
发生黑化是因为'image / jpeg'转换涉及将所有画布像素的Alpha设置为完全不透明(alpha = 255)。问题在于,透明画布像素被着色为完全黑色但透明
。因此,当您将这些黑色像素变为不透明时,结果会变成黑色的jpeg。
This blackening occurs because the 'image/jpeg' conversion involves setting the alpha of all canvas pixels to fully opaque (alpha=255). The problem is that transparent canvas pixels are colored fully-black-but-transparent
. So when you turn these black pixels opaque, the result is a blackened jpeg.
解决方法是手动将所有不透明的画布像素更改为所需的白色,而不是黑色。
The workaround is to manually change all non-opaque canvas pixels to your desired white color instead of black.
通过这种方式,当它们变得不透明时,它们将显示为白色而不是黑色像素。
That way when they are made opaque they will appear as white instead of black pixels.
// change non-opaque pixels to white
var imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
var data=imgData.data;
for(var i=0;i<data.length;i+=4){
if(data[i+3]<255){
data[i]=255;
data[i+1]=255;
data[i+2]=255;
data[i+3]=255;
}
}
ctx.putImageData(imgData,0,0);
这篇关于当从png图像创建jpg图像时,将html canvas黑色背景更改为白色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!