Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**************************************************************************
* resize image in file
**************************************************************************/
export default async function(file,max_pixcels)
{
let canvas = document.createElement('canvas');
canvas.setAttribute('width',0);
canvas.setAttribute('height',0);
canvas.setAttribute('id','canvas');
canvas.style.display = 'none';
document.body.append(canvas);
return new Promise(async resolve => {
let img = new Image();
img.onload = async function()
{
let ratio = img.width / img.height;
if(ratio < 1 && img.width <= max_pixcels)
{
resolve(file);
canvas.remove();
return;
}
if(ratio >= 1 && img.height <= max_pixcels)
{
resolve(file);
canvas.remove();
return;
}
// calculate resized image width/height
let width = max_pixcels;
let height = max_pixcels;
if(img.width > img.height)
width = height * img.width / img.height;
else if(img.width < img.height)
height = width * img.height / img.width;
canvas.setAttribute('width',width);
canvas.setAttribute('height',height);
let ctx = canvas.getContext('2d');
// clear canvas rect
ctx.clearRect(0,0,width,height);
// draw image to canvas
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
// get blob object from canvas and create File instance from blob object
resolve(new File([await getBlobFromCanvas(canvas,file.type)],file.name,{type: file.type,lastModified: file.lastModified}));
// remove canvas from DOM tree
canvas.remove();
};
// load image
let ev = await getImageFromFile(file);
img.src = ev.target.result;
});
}
function getBlobFromCanvas(canvas,type)
{
if(!type)
type = 'image/png';
return new Promise(function(resolve) {
canvas.toBlob(resolve,type);
});
}
function getImageFromFile(file)
{
return new Promise(function(resolve) {
let fr = new FileReader();
fr.onload = resolve;
fr.readAsDataURL(file);
});
}
// polyfill for HTMLCanvasElement.prototype.toBlob
if (!HTMLCanvasElement.prototype.toBlob)
{
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
var canvas = this;
setTimeout(function() {
var binStr = atob( canvas.toDataURL(type, quality).split(',')[1] ),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++ ) {
arr[i] = binStr.charCodeAt(i);
}
callback( new Blob( [arr], {type: type || 'image/png'} ) );
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment