调整大小用JavaScript压缩上传的图像 [英] Resize & compress uploaded image in JavaScript

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

问题描述

我正在建立一个网站,其中会有很多用户上传的图片. 我想在将这些图像上传到服务器之前在客户端调整大小和压缩(最好将其格式更改为.jpg).

I'm building a website which will have a lot of user uploaded images. I would like to resize and compress (preferably change their format to .jpg) these images client side, before uploading them to a server.

人们将如何去做呢? 我找到了一些解决方案,但没有一个真正适用于上传的文件. 我尝试过的最新版本是 Hermite-resize 脚本.应该很简单:

How would one go about doing this? I have found a few solutions, but none that really work on uploaded files. The latest I've tried is the Hermite-resize script. Should be as simple as:

// Get images from input field
var uploadedImages = event.currentTarget.files;


var HERMITE = new Hermite_class(); 
HERMITE.resize_image(uploadedImages[1], 300, 100);

但显然uploadedImages返回为null.虽然我也在其他地方使用它们,所以我100%肯定它们不是null 有人知道如何有效地使用此脚本处理上传的文件吗? 或者,也许有更好的解决方案来在客户端上调整图像的大小或压缩图像?

But apparently the uploadedImages return as null. While I'm also using them elsewhere, so I'm 100% positive they are not null Does anyone know how to use this script effectively with uploaded files? Or is there, perhaps, a better solution to resize/compress images on the client side?

提前谢谢!

推荐答案

我找到了解决我问题的一种方法.这对每个人都不好,但是这个人写了一个小脚本,非常适合我想要完成的事情:

I have found a (sort of) solution to my problem. It's not going to be good for everyone, but this guy wrote a little script that is perfect for what I'm trying to accomplish:

https://stackoverflow.com/a/39235724/6756447

直接使用即可!我添加的唯一一件事是在将返回的Blob推送到数组之前为其赋予时间戳和其原始名称:

Works straight out of the box! The only thing I added was to give the returned blob a timestamp and its original name before pushing it to an array:

var images = event.currentTarget.files

resizeImage({
   file: images[i],
   maxSize: 500
}).then(function(resizedImage) {
   resizedImage.lastModifiedDate = new Date()
   resizedImage.name = images[i].name
   uploadedImages.push(resizedImage)
}).catch(function(error) {
   console.log(error)
})

这篇关于调整大小用JavaScript压缩上传的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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