Skip to content Skip to sidebar Skip to footer

Scaling An Image Proportionally Without Knowing Dimensions

I have a script the retrieves remote images from various URLs. The width and height are unknown variables. I have them displaying on my page and I'm reducing the height to 55px fo

Solution 1:

I had a similar problem but I was using jQuery. But I think you can use the same logic in php to calculate the image size.

var maxWidth = 75; // Max width for the imagevar maxHeight = 77;    // Max height for the imagevar ratio = 0;  // Used for aspect ratiovar width = $(this).width();    // Current image widthvar height = $(this).height();  // Current image height// Check if the current width is larger than the maxif(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        $(this).css("width", maxWidth); // Set new width
        $(this).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
        width = width * ratio;    // Reset width to match scaled image
    }

    // Check if current height is larger than maxif(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        $(this).css("height", maxHeight);   // Set new height
        $(this).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }

Hope this is of any help.

Bah I just realized I brain farted, unknown image size. Disregard the whole thing

Solution 2:

and hey you could always use css to do that! like this answer explains, but you'll have avoid supporting ie6 and maybe ie7 for this feature (you could use conditional comments for resizing with javascript or serverside php script in this scenario)

by the way the above answer does work! but you should add the img programtically and the get the image height and width straight from the object like this and then run the resize function above:

var rimg = new Image();
   rimg.src = "yourimageserverurl";
   var original_height = rimg.height;
   var original_width = rimg.width;
   start the resize function on rimg..

Post a Comment for "Scaling An Image Proportionally Without Knowing Dimensions"