PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

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

 July 27, 2022     aspect-ratio, crop, php, resize     No comments   

Issue

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); 

Solution

    $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); 


Answered By - Nikolai
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing