javascript 如何使用javascript将图像从PNG转换为JPEG?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20744628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a image from PNG to JPEG using javascript?
提问by gauti
I am trying to get image from canvas. PNG image is coming properly but the JPEG is producing a problem. I attached image here.First image is my canvas.Followed by PNG then JPEG.So i want my JPEG image with white background or i need a solution for PNG to JPEG conversion in JS
我正在尝试从画布中获取图像。PNG 图像正常,但 JPEG 产生问题。我在这里附上了图片。第一张图片是我的画布。接着是 PNG 然后是 JPEG。所以我想要我的 JPEG 图像有白色背景,或者我需要一个解决方案,在 JS 中将 PNG 转换为 JPEG
canvas = $('.jSignature')[0];
imgData = canvas.toDataURL();
imgDatajpeg = canvas.toDataURL("image/jpeg");
$(".sigCapHolder").append('<img src='+imgData+' /> ')
$(".sigCapHolder").append('<img src='+imgDatajpeg+' /> ')
回答by
Cause
原因
The reason for this to happen is due to canvas being transparent. However the transparancy color is black with a transparent alpha-channel so it won't show on screen.
发生这种情况的原因是画布是透明的。然而,透明颜色是黑色的,带有透明的 alpha 通道,所以它不会显示在屏幕上。
JPEG on the other side doesn't support alpha-channel so that black color which is the default is stripped of its alpha channel leaving a black background.
另一方面,JPEG 不支持 alpha 通道,因此默认的黑色会从其 alpha 通道中剥离,留下黑色背景。
You PNG supports alpha-channel so it is compatible with the way canvas work.
您的 PNG 支持 alpha 通道,因此它与画布的工作方式兼容。
Solution
解决方案
To get around this you will have to manually draw in a white background on the canvas beforeyou draw in the image:
为了解决这个问题,您必须在绘制图像之前在画布上手动绘制白色背景:
var canvas = $('.jSignature')[0];
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff'; /// set white fill style
ctx.fillRect(0, 0, canvas.width, canvas.height);
/// draw image and then use toDataURL() here
回答by Nwachukwu A. Nnaemeka
this works in firefox, oCanvas.toDataURL("image/jpeg")
这适用于 Firefox,oCanvas.toDataURL("image/jpeg")