I have a form which allows the user to upload a picture. After the user has submitted the form, I\'d like to generate on the front-end a thumbnail for each picture and then
Building on top of what Allesandro wrote to something more pragmatic.
The function takes a file from the File API and tries to fit it in the boundBox while preserving the aspect ratio. Nothing is drawn, but instead you get back a Promise that spits the dataUrl generated.
// Creates a thumbnail fitted insize the boundBox (w x h)
generateThumbnail(file, boundBox){
if (!boundBox || boundBox.length != 2){
throw "You need to give the boundBox"
}
var scaleRatio = Math.min(...boundBox) / Math.max(file.width, file.height)
var reader = new FileReader();
var canvas = document.createElement("canvas")
var ctx = canvas.getContext('2d');
return new Promise((resolve, reject) => {
reader.onload = function(event){
var img = new Image();
img.onload = function(){
var scaleRatio = Math.min(...boundBox) / Math.max(img.width, img.height)
let w = img.width*scaleRatio
let h = img.height*scaleRatio
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
return resolve(canvas.toDataURL(file.type))
}
img.src = event.target.result;
}
reader.readAsDataURL(file);
})
}
It can be used like below
generateThumbnail(file, [300, 300]).then(function(dataUrl){
console.log(dataUrl)
})