Re-scaling an image by a percentage

Hi guys!

I’m losing the plot here, so I need some help.

I’m working on a news system within a CMS and the idea is to include images from elsewhere in the website (typically product photography of various sizes), but they are mixed landscape and portrait format. The only thing that will be fixed (after they’ve been included in the news item) is their width, which will be 170 pixels wide.

However, to make all of the images that width, they height has to be scaled proportionally, which I thought I had working. Here’s what I have so far:

// Load image and get image size
$image_source = imagecreatefromjpeg( $image );
$width = imagesx( $image_source );
$height = imagesy( $image_source );

$width_new = '170';

if ($width < $height):

	$percentage = (100 * ($width_new / $height));

	$height_new = round($width * (1 - ($percentage / 100)));

elseif ($width > $height):

	$percentage = (100 * ($width_new / $height));

	$height_new = round($width * (1 - ($percentage / 100)));

endif;

When testing the calculations separately, they work. But when I add them into the live website, they go wonky.

I’ve just dropped the second part of the conditional statement in, as I know it needs swapping around, but I have no clue what the hell is going on with the numbers in the first part, mathematics not being a great love of mine!

You don’t need any if statements here at all.

All you have is the equation:


 width     170
------- = -----
 height     x

so


     170 * height
x = --------------
        width

or


$height_new = ( $width_new * $height ) / $width;

:slight_smile:

ScallioXTX, that’s excellent!

Thanks for the help.

Don’t forget a [fphp]round/fphp or (int) to get whole pixels.

Yeah, I was already aware of the rounding issue (see the code I posted above). Thanks all the same!