Skip to content

Instantly share code, notes, and snippets.

@rodrigoespinozadev
Forked from vishalsrini/resize.js
Created September 19, 2018 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigoespinozadev/5f90b1ba7af7dd8fbabe12f5baff145f to your computer and use it in GitHub Desktop.
Save rodrigoespinozadev/5f90b1ba7af7dd8fbabe12f5baff145f to your computer and use it in GitHub Desktop.
A simple JavaScript to resize an image and create a blob out of it
window.resize = (function () {
'use strict';
function Resize() {}
Resize.prototype = {
init: function(outputQuality) {
this.outputQuality = (outputQuality === 'undefined' ? 0.8 : outputQuality);
},
photo: function(file, maxSize, outputType, callback) {
var _this = this;
var reader = new FileReader();
reader.onload = function (readerEvent) {
_this.resize(readerEvent.target.result, maxSize, outputType, callback);
}
reader.readAsDataURL(file);
},
resize: function(dataURL, maxSize, outputType, callback) {
var _this = this;
var image = new Image();
image.onload = function (imageEvent) {
// Resize image
var canvas = document.createElement('canvas'),
width = image.width,
height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
_this.output(canvas, outputType, callback);
}
image.src = dataURL;
},
output: function(canvas, outputType, callback) {
switch (outputType) {
case 'file':
canvas.toBlob(function (blob) {
callback(blob);
}, 'image/jpeg', 0.8);
break;
case 'dataURL':
callback(canvas.toDataURL('image/jpeg', 0.8));
break;
}
}
};
return Resize;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment