Skip to content

Instantly share code, notes, and snippets.

@ychevarrias
Created August 1, 2019 04:06
Show Gist options
  • Save ychevarrias/7a815a21f6ce5332266ae3a5e89a9ebd to your computer and use it in GitHub Desktop.
Save ychevarrias/7a815a21f6ce5332266ae3a5e89a9ebd to your computer and use it in GitHub Desktop.
Redimensión de imágenes con javascript | Canvas crop, scale image
compress_async = (e) => {
return new Promise((resolve, reject) => {
const width = 1080;
const height = 1080;
const fileName = e.target.files[0].name;
const reader = new FileReader();
var file = null;
reader.readAsDataURL(e.target.files[0]);
const img = new Image();
const img_rst = new Image();
reader.onload = event => {
img.src = event.target.result;
img.onload = () => {
const elem = document.createElement('canvas');
elem.width = width;
elem.height = height;
const ctx = elem.getContext('2d');
// img.width and img.height will contain the original dimensions
let opts = cropper_square(img.width, img.height, width/height);
console.log(opts.width, opts.height, width, height)
ctx.drawImage(
img, opts.width_offset,opts.height_offset,
opts.width, opts.height,
0, 0, width, height
);
ctx.canvas.toBlob((blob) => {
const new_file = new File([blob], fileName, {
type: 'image/jpeg',
lastModified: Date.now()
});
resolve({new_file: new_file, blob: blob});
}, 'image/jpeg', 1);
},
reader.onerror = error => console.log(error);
};
})
}
function cropper_square(w, h, rel=1){
let actual_rel = w/h;
let width = 0;
let height = 0;
let width_offset = 0;
let height_offset = 0;
let sample = w
let sample_dimension = [sample, parseInt(sample/rel)]
let completed = false
let tried = false
while(completed == false){
if (w >= sample_dimension[0] && h >= sample_dimension[1]){
completed = true;
}else{
sample = parseInt(h * rel)
if (-1 < w - sample < 1 && !tried){
sample++;
tried = true;
}
console.log(sample, parseInt(sample/rel), sample/rel)
sample_dimension = [sample, parseInt(sample/rel)]
}
}
let width_diff = w - sample_dimension[0];
let height_diff = h - sample_dimension[1];
if(width_diff > 1){
width_offset = parseInt(width_diff/2)
}else if(height_diff > 1){
height_offset = parseInt(height_diff/2)
}
let rst = {
width_offset: width_offset,
height_offset: height_offset,
width: sample_dimension[0],
height: sample_dimension[1],
}
console.log(rst);
return rst
}
const img_rst = new Image();
document.body.appendChild(img_rst)
const input_file = document.createElement('input')
input_file.type = 'file'
input_file.addEventListener("change", function (event) {
compress_async(event).then(rsp => {
console.log("img_resized => ",rsp.new_file, rsp.blob)
reader = new FileReader();
reader.readAsDataURL(rsp.blob)
reader.onload = event => {
img_rst.src = event.target.result
}
});
});
input_file.click()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment