Html5 Canvas调整大小 [英] Html5 Canvas resize

查看:276
本文介绍了Html5 Canvas调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用canvas在客户端调整图像大小,然后将该图像上传到服务器。我的意图是将图像调整为其原始尺寸的一半,并希望看到文件大小减小。但调整后的图像尺寸总是比原始尺寸大。



例如,我改变了2.5 MB JPEG图像文件的大小,尺寸为2592 x 1936至1296 x 968(JPEG文件)并尝试将其上传到服务器。在服务器上,我看到该文件以3.5 MB大小保存。



在使用html5画布调整大小时我们可以做些什么,这样如果我们减小尺寸,我们可以预期文件大小会有一些减小,比如压缩。

解决方案

如果您使用的是toDataURL,则可以将第二个参数设置为介于0.0和1.0之间的数字。这是JPEG质量等级,1.0意味着非常高的质量和非常大的图像,接近0.0意味着质量较低的较小图像。



所以,例如,你可以尝试:

  data = downsizedCanvas.toDataURL(image / jpeg,0.2); 

这是w3c参考中的描述: www.w3.org:toDataURL

<看起来好像Firefox中存在一个忽略质量的问题,所以你可能需要在一些现代浏览器中测试。


Am using canvas to resize image at the client side and then upload that image to the server. My intention was to resize the image to half of its original dimensions and wanted to see a decrease in the file size. But the resized image size is always greater than the original.

For example,

I was resizing a 2.5 MB JPEG image file with dimensions 2592 x 1936 to 1296 x 968 (JPEG file) and tried to upload it to the server. On the server I see that the file is saved with the 3.5 MB size.

Is there something that we can do while resizing with html5 canvas so that if we are decreasing the dimensions we could expect some decrease in the file size like compression.

解决方案

If you are using toDataURL, you can set the second argument to a number between 0.0 and 1.0. This is the JPEG quality level, with 1.0 meaning very high quality and a very large image and nearer to 0.0 meaning lower quality smaller image.

So, for example, you could try:

 data = downsizedCanvas.toDataURL("image/jpeg", 0.2);

Here's a description in the w3c reference: www.w3.org: toDataURL

It looks like there has been a bug in Firefox to do with ignoring the quality, so you might need to test in some modern browsers.

这篇关于Html5 Canvas调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆