When you allow users to submit content, and allow that content to include images, there’s always a chance that some user will submit a really large image that will break your layout. One way to solve that is to check the content for large images and resize them using a server-side program. However, sometimes, that is simply not possible. In those cases, we use what’s left- 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 35 36 37 38 39 40 41 42 43 44 | $(document).ready(function() { ( function(maxht, maxwt, minht, minwt) { var imgs = document.getElementsByTagName('img'); // Image resizing function var resize_image = function(img, newht, newwt) { img.height = newht; img.width = newwt; }; for (var i = 0; i < imgs.length; i++) { // Set a variable for the current image to make the code // make more sense. 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); } // We need to do some magic now. else { var newdim = [img.height, img.width]; // Sort out the height first. newdim[0] = minht; // The logic behind this is that if ratio = ht / wt, // then wt = ht / ratio. newdim[1] = newdim[0] / old_ratio; // Do we still have to sort out the width? if (newdim[1] > maxwt) { // Just do what we did with the height newdim[1] = minwt; newdim[0] = newdim[1] * old_ratio; } // So yeah, resize the image resize_image(img, newdim[0], newdim[1]); } } } } )(500, 500, 500, 500); }); |
To change the dimensions above which images should be resized, and the dimensions to which it should be resized, you’d want to edit line 43.
This script depends up on jQuery only to make it run after the page has loaded. If you want to get it to work without jQuery, you’d only need to swap out that part. You could also use jQuery’s wrap function to put the resized image in a frame with a notice and stuff. You can see that in action here.
Feel free to use this (as long as you give credit), and let me know if you do.

This work by Aetus Designs is licensed under a Creative Commons Attribution 3.0 Unported License.
Tags: images, javascript, snippet