Resize Large Images with Javascript
This function will resize any images with dimensions above a specified set of dimensions while preserving the aspect ratio. Be sure to call the function only after every image has been loaded.
(Javascript)1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | // 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]);
}
}
}
}
|
You can modify this code a bit to make it a little fancy. For an example, look at this demo, in which I have modified it using jQuery.
I can be contacted at the email address:
.
There is a list of software, etc. used to build this website here:
Credits.
.
There is a list of software, etc. used to build this website here:
Credits.