Last active
September 6, 2024 17:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
how to use it?