[英]Using HTML Canvas + Javascript to optimize and image + reduce filesize
I am making a Chrome extension which automatically takes a screenshot of the visible tab and download a JPG to your filesystem. 我正在制作一个Chrome扩展程序,该程序会自动拍摄可见标签的屏幕截图,然后将JPG下载到您的文件系统中。 That all works fine but the images are very large (~400kb for a 1280x720px image) and I want to optimize them (ideally around 40kb).
一切正常,但图像非常大(对于1280x720px图像,约为400kb),我想对其进行优化(理想情况下约为40kb)。
Here is the code I'm using: 这是我正在使用的代码:
var image = new Image();
image.onload = function() {
var canvas = screenshot.content;
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
// save the image
var link = document.createElement('a');
link.download = shotname + ".jpg";
link.href = screenshot.content.toDataURL();
link.click();
screenshot.data = '';
};
image.src = screenshot.data;
How can I optimize the image to reduce quality and filesize? 如何优化图像以降低质量和缩小文件大小? I'd like to play around with different quality options so I can see what an acceptable use-case is.
我想尝试不同的质量选项,以便了解什么是可以接受的用例。
You can use JPEG and a quality setting like this: 您可以使用JPEG和如下质量设置:
link.href = screenshot.content.toDataURL("image/jpeg", 0.3);
The quality is in the range [0, 1]. 质量在[0,1]范围内。 If you don't specify any image type, the default will be PNG, which is relative large in many cases.
如果您未指定任何图像类型,则默认值为PNG,在许多情况下该尺寸相对较大。
Just be aware of that you will loose the alpha-channel when using JPEG. 请注意,使用JPEG时,您将失去alpha通道。
Additionally you can blur the image slightly (see f.ex. my realtime-blur or stack-box blur ). 另外,您可以稍微模糊图像(请参阅f.ex.我的实时模糊或堆栈框模糊 )。 Blurring filters some of the high frequencies that are hard to compress.
模糊会滤除一些难以压缩的高频。
You could encode the url in jpg format. 您可以将网址编码为jpg格式。
The second parameter specifies the quality of the resulting jpg. 第二个参数指定生成的jpg的质量。
link.href = screenshot.content.toDataURL('image/jpeg', 0.6);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.