Skip to content

Instantly share code, notes, and snippets.

@vishalsrini
Last active June 27, 2023 03:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save vishalsrini/e502ab43784e3027034c3f33de70a0fa to your computer and use it in GitHub Desktop.
Save vishalsrini/e502ab43784e3027034c3f33de70a0fa 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;
}());
@martinpodkrivacky
Copy link

how to use it?

@Nemra1
Copy link

Nemra1 commented Mar 16, 2023

how to use it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment