Javascript 如何在使用“toDataURL”方法转换画布时设置图像质量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14383557/
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 set the image quality while converting a canvas with the "toDataURL" method?
提问by jedierikb
I want to set the quality factor when I encode a canvas element to jpg.
我想在将画布元素编码为 jpg 时设置品质因数。
var data = myCanvas.toDataURL( "image/jpeg" );
It does not give me a quality option. Is there an alternative library I can use?
它没有给我一个高质量的选择。有我可以使用的替代库吗?
Related: what is the default quality setting used by the different browsers?
相关:不同浏览器使用的默认质量设置是什么?
回答by limoragni
The second argument of the function is the quality. It ranges from 0.0 to 1.0
该函数的第二个参数是质量。它的范围从 0.0 到 1.0
canvas.toDataURL(type,quality);
Hereyou have extended information
这里有扩展信息
And I don't think it's possible to know the quality of the image once is converted. As you can see on this feedlethe only information you get when printing the value on the console is the type and the image code itself.
而且我认为一旦转换就不可能知道图像的质量。正如您在此feedle上看到的,在控制台上打印值时您获得的唯一信息是类型和图像代码本身。
Here's a snippet of code I made to know the default value of the quality used by the browser.
这是我为了解浏览器使用的质量的默认值而制作的一段代码。
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
var url = c.toDataURL('image/jpeg');
var v = 0
for(var i = 0; i < 100; i++ ){
v += 0.01;
x = parseFloat((v).toFixed(2))
var test = c.toDataURL('image/jpeg', x);
if(test == url){
console.log('The default value is: ' + x);
}
}
Basically I thought that the change on the image itself would be reflected on the base64 string. So the code just try all the possible values on the toDataURL()method and compares the resulting string with the default one. And it seems to work. For chromium I get 0.92.
基本上我认为图像本身的变化会反映在 base64 字符串上。所以代码只是尝试方法上所有可能的值toDataURL(),并将结果字符串与默认字符串进行比较。它似乎有效。对于铬,我得到 0.92。
Hereis the working example on a fiddle.
这是小提琴的工作示例。
回答by Chuck Le Butt
Using Fabric.js, a very simple and human-readable way, is this:
使用Fabric.js是一种非常简单且人类可读的方式,是这样的:
canvas.toDataURL({
format: 'jpeg',
quality: 0.8
});
This also allows you to have other options, giving you the ability to crop the image, etc:
这也允许您有其他选项,使您能够裁剪图像等:
canvas.toDataURL({
format: 'png',
left: 300,
top: 250,
width: 200,
height: 150
})
jsFiddle: http://jsfiddle.net/7f9bqs00/30/
jsFiddle:http: //jsfiddle.net/7f9bqs00/30/

