Change html canvas black background to white background when creating jpg image from png image(从png图像创建jpg图像时将html画布黑色背景更改为白色背景)
问题描述
我有一个 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画布黑色背景更改为白色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从png图像创建jpg图像时将html画布黑色背景更改为白色背景


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01