当使用 toDataUrl() 设置图像标签的来源时,我发现保存时的图像比原始图像大很多。
在下面的示例中,我没有为 toDataUrl 函数指定第二个参数,因此使用了默认质量。这导致图像比原始图像尺寸大得多。当为全质量指定 1 时,生成的图像会更大。
有谁知道为什么会发生这种情况或我该如何阻止它?
// create image
var image = document.createElement('img');
// set src using remote image location
image.src = 'test.jpg';
// wait til it has loaded
image.onload = function (){
// set up variables
var fWidth = image.width;
var fHeight = image.height;
// create canvas
var canvas = document.createElement('canvas');
canvas.id = 'canvas';
canvas.width = fWidth;
canvas.height = fHeight;
var context = canvas.getContext('2d');
// draw image to canvas
context.drawImage(image, 0, 0, fWidth, fHeight, 0, 0, fWidth, fHeight);
// get data url
dataUrl = canvas.toDataURL('image/jpeg');
// this image when saved is much larger than the image loaded in
document.write('<img src="' + dataUrl + '" />');
}
谢谢 :D
这是一个示例,不幸的是,该图像不能跨域,因此我只需要提取其中一个 jsfiddle 图像。
图像是 7.4kb,如果你保存正在输出的图像,你会看到它是 10kb。使用更详细的图像时,差异会更加明显。如果将 toDataUrl 质量设置为 1,则图像为 17kb。
我也在为此使用 FireFox 10,当使用 Chrome 时,图像尺寸仍然更大,但没有那么多。