Created
December 6, 2016 08:28
-
-
Save MeTe-30/cbed996fd760e6c26cc1f1fcb1607496 to your computer and use it in GitHub Desktop.
Resize & Optimize Image, create Thumbnail | Javascript
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
// UseCases: | |
// function CB(dataUrl, newSize) { console.info(newSize.w, newSize.h); }; | |
// To set specific width: resizeImage(url, {w: 200}, CB); | |
// To set specific height: resizeImage(url, {h: 200}, CB); | |
// To rediuce size by percent: resizeImage(url, {r: .5}, CB); | |
// To change export quality add {q: .5} (default & max is 1) | |
// resizeImage(url, {r: .5, q: .5}, CB); | |
function resizeImage(url, rate, callback) { | |
rate = rate || {}; | |
rate.q = rate.q || 1; | |
rate.r = rate.r || 1; | |
var image = new Image(); | |
image.setAttribute('crossOrigin', 'anonymous'); | |
image.onload = function () { | |
var canvas = document.createElement('canvas'); | |
if (rate.w) { | |
canvas.width = rate.w; | |
canvas.height = this.naturalHeight * rate.w / this.naturalWidth; | |
} | |
else if (rate.h) { | |
canvas.width = this.naturalWidth * rate.h / this.naturalHeight; | |
canvas.height = rate.h; | |
} else { | |
canvas.width = this.naturalWidth * rate.r; | |
canvas.height = this.naturalHeight * rate.r; | |
} | |
canvas.getContext('2d').drawImage(this, 0, 0); | |
callback(canvas.toDataURL('image/png', rate.q), { w: canvas.width, h: canvas.height }); | |
}; | |
image.src = url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment