Skip to content

Instantly share code, notes, and snippets.

@ivanhoe011
Created December 21, 2014 14:11
Show Gist options
  • Save ivanhoe011/f469cf1c028415fd11df to your computer and use it in GitHub Desktop.
Save ivanhoe011/f469cf1c028415fd11df to your computer and use it in GitHub Desktop.
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