View Full Version : JS Proportional Image Resize Problem

12-11-2007, 10:40 AM
Hi, I've been struggling away trying to come up with a technique for resizing and positioning images uploaded by users of a CMS i'm developing. I want any images uploaded to be no wider than 500px and no taller than 300px. I want to resize the images proportionally and in a way which will work in most browsers (tried using CSS max width and max height and these only seemed to resize proportionally on Firefox).

Anyway, I've written a little bit of basic Javascript which almost works, apart from instances where the width does not exceed the max of 500. In this situation (where the width < 500 and the height >300), although I allocate a new height and width to the image, it does not display the new dimensions. In my code, I have used an alert to print out the new height and width in these situations - the alert message correct displays the new dimensions but these don't take effect on the image displayed.

An example of the problem is at the following URL, where the first of the 3 images has not resized correctly, while the other 2 have successfully.

Apologies for the ramble, if this makes any sense at all i'd be grateful for any help (fairly inexperienced with Javascript which is probably fairly obvious)!

function checkImages() {
var maxWidth = 300;
var ps = document.getElementById('content').getElementsByTagName('p');
//loop through each paragraph and check the images attached
for (i = 0; i < ps.length; i++) {
var img = ps[i].getElementsByTagName('img')[0];

if (img != null) {
var height = img.height;
var width = img.width;
var clone=img.cloneNode(true);

//check to see if image needs to be resized - 500 is the maximum width allowed
if (width>500) {
var reduction = 500 / width;
clone.style.width = '500px';
//set new height proportional to new width
var newHeight = Math.round(img.height * reduction) ;
clone.style.height = newHeight + 'px';
width = 500;

//check to see if image needs to be resized - 300 is the maximum height allowed
if (height>300) {
var reduction = 300 / height;
clone.style.height = '300px';
//set new width proportional to new width
var newWidth = Math.round(img.width * reduction) ;
clone.style.width = newWidth + 'px';
width = newWidth;
alert("width =" + clone.style.width);
//if the image is too wide to wrap the text alongside it, move the image underneath the text
if (width > maxWidth) {
clone.style.marginRight = 575 - width + 'px';
clone.style.marginBottom = '40px';
clone.style.marginTop = '20px';
//set min height for paragraph
if (img.height < 250)
ps[i].style.minHeight = img.height + 60 + 'px';
ps[i].style.minHeight = '310px';

Here's the code....

rnd me
12-11-2007, 01:08 PM
it looks on in firefox for me.

in ie7, i think the size is fine, its possibly too far down

/* Rule 9 of ../css/styles.css */ #sidemenu UL { MARGIN-TOP: 160px; MARGIN-LEFT: -30px}

unless you are talking about something else entirely...