Created
December 31, 2016 03:25
-
-
Save avishaan/388fb78dff1fe15141720df03ce66a76 to your computer and use it in GitHub Desktop.
adjust image size
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
// Call this function *after* the page is completely loaded! | |
function resize_images(maxht, maxwt, minht, minwt) { | |
var imgs = document.getElementsByTagName('img'); | |
var resize_image = function(img, newht, newwt) { | |
img.height = newht; | |
img.width = newwt; | |
}; | |
for (var i = 0; i < imgs.length; i++) { | |
var img = imgs[i]; | |
if (img.height > maxht || img.width > maxwt) { | |
// Use Ratios to constraint proportions. | |
var old_ratio = img.height / img.width; | |
var min_ratio = minht / minwt; | |
// If it can scale perfectly. | |
if (old_ratio === min_ratio) { | |
resize_image(img, minht, minwt); | |
} | |
else { | |
var newdim = [img.height, img.width]; | |
newdim[0] = minht; // Sort out the height first | |
// ratio = ht / wt => wt = ht / ratio. | |
newdim[1] = newdim[0] / old_ratio; | |
// Do we still have to sort out the width? | |
if (newdim[1] > maxwt) { | |
newdim[1] = minwt; | |
newdim[0] = newdim[1] * old_ratio; | |
} | |
resize_image(img, newdim[0], newdim[1]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment