Skip to content
Advertisement

How do I Resize images to fixed width & height while maintaing aspect ratio in PHP?

I am trying to batch resize images to the size of 250 x 250 in PHP

All source images are way bigger than 250 x 250 so that is helpful.

I want to maintain aspect ratio but make them all 250 x 250. I know that a portion of the image will be cropped off to do this. That is not an issue for me

The problem is that my current script only works on width and makes height according to aspect but sometimes, the image will now end up being let’s say, 250 x 166. I can’t use that.

In that cause It would need to be resized in the opposite manner (height to width)

How would the script have to look to always make the final image 250 x 250 without stretching. Again, I don’t care if there is cropping. I assume there is going to be an else in the somewhere but this is way over my head now. I am more of a front end guy.

Any help would be great.

Below is just the relevant portion of my full script:

$width = 250;
$height = true;

 // download and create gd image
 $image = ImageCreateFromString(file_get_contents($url));

 // calculate resized ratio
 // Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
 $height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;

 // create image 
 $output = ImageCreateTrueColor($width, $height);

 ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));

 // save image
 ImageJPEG($output, $destdir, 100); 

Advertisement

Answer

    $newWidth = 250;
    $newHeight = 250;

    // download and create gd image
    $image = ImageCreateFromString(file_get_contents($url));
    $width = ImageSX($image);
    $height = ImageSY($image);

    $coefficient =  $newHeight / $height;
    if ($newHeight / $width > $coefficient) {
        $coefficient = $newHeight / $width;
    }

    // create image
    $output = ImageCreateTrueColor($newWidth, $newHeight);

    ImageCopyResampled($output, $image, 0, 0, 0, 0, $width * $coefficient, $height * $coefficient, $width, $height);

   // save image
   ImageJPEG($output, $destdir, 100); 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement