Created
December 21, 2014 14:11
-
-
Save ivanhoe011/f469cf1c028415fd11df to your computer and use it in GitHub Desktop.
From http://alfonsoml.blogspot.com/search/label/SimpleUploads Resize image before upload
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
function scaleImage(ev) | |
{ | |
var data = ev.data, | |
editor = ev.editor; | |
var img = data.image; | |
// maximum size allowed for images | |
var maxX = 400; | |
var maxY = 300; | |
var imgX = img.width; | |
var imgY = img.height; | |
if (imgX == 0 || imgY == 0) | |
{ | |
alert("Ops, the image doesn't seem to be valid"); | |
ev.cancel(); | |
return; | |
} | |
// if it's smaller, get out | |
if (imgX <= maxX && imgY <= maxY) | |
return; | |
var ratio = imgX / imgY; | |
if ((maxX / maxY) > ratio) | |
maxX = Math.round(maxY * (ratio)); | |
else | |
maxY = Math.round(maxX / (ratio)); | |
var canvas = document.createElement("canvas"); | |
canvas.width = maxX; | |
canvas.height = maxY; | |
var ctx = canvas.getContext('2d'); | |
ctx.drawImage(img, 0, 0, maxX, maxY); | |
if ( /\.jpe?g$/.test(data.name)) | |
{ | |
// You could adjust here the quality of jpg | |
evData.file = canvas.toDataURL("image/jpeg", 0.9); | |
} | |
else | |
data.file = canvas.toDataURL("image/png"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment