如何在浏览器中通过 Javascript 压缩图像? [英] How to compress an image via Javascript in the browser?

查看:28
本文介绍了如何在浏览器中通过 Javascript 压缩图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL;DR;

有没有办法在上传之前直接在浏览器端压缩图像(主要是 jpeg、png 和 gif)?我很确定 JavaScript 可以做到这一点,但我找不到实现它的方法.

Is there a way to compress an image (mostly jpeg, png and gif) directly browser-side, before uploading it ? I'm pretty sure JavaScript can do this, but I can't find a way to achieve it.


这是我想要实现的完整场景:


Here's the full scenario I would like to implement:

  • 用户访问我的网站,并通过 input type="file" 元素选择图像,
  • 此图片是通过 JavaScript 检索的,我们会进行一些验证,例如正确的文件格式、最大文件大小等,
  • 如果一切正常,页面上会显示图像预览,
  • 用户可以进行一些基本操作,例如将图像旋转 90°/-90°、按照预先定义的比例裁剪等,或者用户可以上传另一张图像并返回到步骤 1,
  • 当用户满意时,编辑后的图像会被压缩并在本地保存"(不是保存到文件中,而是保存在浏览器内存/页面中),-
  • 用户在表单中填写姓名、年龄等数据,
  • 用户点击完成"按钮,然后将包含数据+压缩图像的表单发送到服务器(没有AJAX),

到最后一步的完整过程应该在客户端完成,并且应该兼容最新的 Chrome 和 Firefox、Safari 5+ 和 IE 8+.如果可能,只应使用 JavaScript(但我很确定这是不可能的).

The full process up to the last step should be done client side, and should be compatible on latest Chrome and Firefox, Safari 5+ and IE 8+. If possible, only JavaScript should be used (but I'm pretty sure this is not possible).

我现在还没有写任何代码,但我已经考虑过了.通过文件API可以在本地读取文件,可以使用Canvas 元素,但我找不到进行图像压缩部分的方法.

I've not code anything right now, but I've thought about it already. File reading locally is possible via File API, image previewing and editing could be done using Canvas element, but I can't find a way to do the image compression part.

根据 html5please.comcaniuse.com,支持这些浏览器是相当困难的(感谢 IE),但可以使用 polyfill 来完成,例如 FlashCanvasFileReader.

According to html5please.com and caniuse.com, supporting those browser is quite hard (thanks to IE), but could be done using polyfill such as FlashCanvas and FileReader.

实际上,目标是减小文件大小,因此我将图像压缩视为一种解决方案.但是,我知道上传的图像将显示在我的网站上,每次都在同一个地方,而且我知道这个显示区域的尺寸(例如 200x400).因此,我可以调整图像大小以适应这些尺寸,从而减小文件大小.我不知道这种技术的压缩比是多少.

Actually, the goal is to reduce file size, so I see image compression as a solution. But, I know that uploaded images are going to be displayed on my website, every time at the same place, and I know the dimension of this display area (eg. 200x400). So, I could resize the image to fit those dimensions, thus reducing file size. I have no idea what would be the compression ratio for this technique.

你怎么看?你有什么建议要告诉我吗?您知道在 JavaScript 中压缩图像浏览器端的任何方法吗?感谢您的回复.

What do you think ? Do you have any advice to tell me ? Do you know any way to compress an image browser-side in JavaScript ? Thanks for your replies.

推荐答案

简而言之:

  • 使用带有 .readAsArrayBuffer 的 HTML5 FileReader API 读取文件
  • 使用文件数据创建一个 Blob 并使用 window.URL.createObjectURL(blob)
  • 创建新的 Image 元素并将其 src 设置为文件 blob url
  • 将图像发送到画布.画布大小设置为所需的输出大小
  • 通过 canvas.toDataURL("image/jpeg",0.7) 从画布取回缩小的数据(设置您自己的输出格式和质量)
  • 将新的隐藏输入附加到原始表单并将 dataURI 图像基本上作为普通文本传输
  • 在后端,读取 dataURI,从 Base64 解码并保存

来源:代码.

这篇关于如何在浏览器中通过 Javascript 压缩图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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