Shrink Image (JavaScript)
This function shrinks an image, so its dimensions are no bigger than the maximum dimensions you define.
// get new dimensions so it fits within the maximum // o = original dimensions / image, m = maximum dimensions function shrink(o, m) { // r = resized var r = {width: o.width, height: o.height}; // if an image, rather than an object, resize it if(o.nodeName && o.nodeName.toLowerCase() == "img") r = o; if(r.width > m.width) { r.height = r.height * (m.width / r.width); r.width = m.width; if(r.height > m.height) { r.width = r.width * (m.height / r.height); r.height = m.height; } } else if(r.height > m.height) { r.width = r.width * (m.height / r.height); r.height = m.height; } return r; }
To use, simply supply the image and the dimensions to constrain it to:
var image = document.getElementById("image"); var max = {width: 1024, height: 768}; shrink(image, max);
It also works with an object instead of an image, for non-image related dimension calculation.
var original = {width: 1200, height: 960}; var max = {width: 1024, height: 768}; var shrunk = shrink(original, max);
Comments