math-challenged needs formula to constrain images for php + gd image manipulation
August 13, 2007 3:15 PM
Subscribe
I need a formula or actual php code to generate a new height and width that will constrain the image between a maximum height and a maximum width while retaining the correct proportions of the original image.
I'm working on some php code to resize images via gd that are uploaded. I've got the upload and saving code going, and I have successfully coded the parts where I'm given a width OR a height to resize the image.
My problem is that, for another application, I need to set a max width AND a max height and resize the image within those limits while keeping the proportions of the orginal image.
Example:
max_height = 80
max_width = 140
If an uploaded image is 200x200, the resized dimensions would be 80x80 (constrained by the max height of 80). But, my problem is being able to come up with the formula/code that will do that and also for harder ones such as where the uploaded image is something like 500w by 200h. I need a formula or php code by which I end up with dimensions for the uploaded image where the width is no wider than 140 and the height no higher than 80 but where the dimensions are proportionate to 500:200.
Thanks!
Steven
posted by sjarvis to computers & internet (10 comments total)
2 users marked this as a favorite
//if not forcing, we'll prefer having width correct first. $new_width=$max_width; $new_height= floor(($max_width/$width)*$height); if ($new_height>$max_height) { $new_height=$max_height; $new_width=floor(($max_height/$height)*$width); }posted by fishfucker at 3:37 PM on August 13, 2007