-
-
Save jgaiao/2f32536ce7b41c5b6b15697b6621f5d5 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 hidden or 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
| var Resize = function(outputQuality) { | |
| this.outputQuality = (outputQuality === 'undefined' ? 0.8 : outputQuality); | |
| this.photo = function(file, maxWidth, maxHeight, outputType, callback) { | |
| var _this = this; | |
| var reader = new FileReader(); | |
| reader.onloadend = function(readerEvent) { | |
| _this.resize(readerEvent.target.result, maxWidth, maxHeight, outputType, callback); | |
| } | |
| reader.readAsDataURL(file); | |
| } | |
| this.resize = function(dataURL, maxWidth, maxHeight, 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 > maxWidth) { | |
| height *= maxWidth / width; | |
| width = maxWidth; | |
| } | |
| } else { | |
| if (height > maxHeight) { | |
| width *= maxHeight / height; | |
| height = maxHeight; | |
| } | |
| } | |
| canvas.width = width; | |
| canvas.height = height; | |
| canvas.getContext('2d').drawImage(image, 0, 0, width, height); | |
| _this.output(canvas, outputType, callback); | |
| } | |
| image.src = dataURL; | |
| } | |
| this.output = function(canvas, outputType, callback) { | |
| switch (outputType) { | |
| case 'file': | |
| canvas.toBlob(function(blob) { | |
| callback(blob); | |
| }, 'image/jpeg', this.outputQuality); | |
| break; | |
| case 'dataURL': | |
| callback(canvas.toDataURL('image/jpeg', this.outputQuality)); | |
| break; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment