问题描述
我有一个 canvas
加载了 png
图像.我通过 .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画布黑色背景更改为白色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!