问题
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.
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);
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?
Thanks in advance!
回答1:
I have tried to work on hermite but it is not good class because it gives to me error constantly hence you can use below code, on fiddle, also hermit class wants to img element id
HTML
<input type="file" id="fileOpload"><br>
<img src="" alt="Image preview..." id="image">
<canvas id="canvas" height=500 width=500></canvas>
Javascript
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
var percentage = 0.75;
reader.addEventListener("load", function () {
preview.src = reader.result;
preview.onload = function () {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.height = canvas.width * (preview.height / preview.width);
var oc = document.createElement('canvas'),octx = oc.getContext('2d');
oc.width = preview.width * percentage;
oc.height = preview.height * percentage;
canvas.width = oc.width;
canvas.height = oc.height;
octx.drawImage(preview, 0, 0, oc.width, oc.height);
octx.drawImage(oc, 0, 0, oc.width, oc.height);
ctx.drawImage(oc, 0, 0, oc.width, oc.height,0, 0, canvas.width, canvas.height);
}
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
document.getElementById('fileOpload').addEventListener('change', previewFile);
回答2:
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
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)
})
来源:https://stackoverflow.com/questions/46907374/resize-compress-uploaded-image-in-javascript