使用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的图片。 http://jsfiddle.net/ptSUd/ 这张图片大小为7.4kb,如果你保存输出的图片,会发现它大小为10kb。更详细的图片差异更加明显。如果将toDataUrl质量设置为1,则该图片的大小为17kb。
我也在使用Firefox 10,在Chrome中使用时,图像尺寸仍然较大,但差别没有那么大。
base64
编码存储(增加1/3的大小)。在浏览器中存储算法可能不如原始使用方式优化。 - kirilloid