How to reduce size of Image using Imagick to a set width?

2.5k views Asked by At

I have a photo gallery where the cover photo has images of 290px set width and the height can be anything. I'm going for a Pinterest type of effect. I'm trying to do this using PHP and Imagick, but cannot seem to figure it out. Can someone assist?

Here is the function that I have so far, but just getting small images. I read somewhere that setting the height to a number higher makes it auto but to no avail.

function thumbnailImage($imagePath,$real_target_pathThumb) {

                $imagick = new Imagick($imagePath);
                $imagick->thumbnailImage(290, 9999, true, true);

                $imagick->writeImage($real_target_pathThumb);

            };
1

There are 1 answers

0
ptkoz On BEST ANSWER

Since thumbnailImage function does not support one-dimension limits, the best approach is to use aspect ratio and calculate thumbnail height manually. This is as simple as:

$imagick = new Imagick($imagePath);
$imagick->thumbnailImage(290, (int)(290 * $imagick->getImageHeight() / $imagick->getImageWidth()));

Also you can omit (or set to false) fill parameter from imagick's thumbnailImage method, like this

$imagick->thumbnailImage(290, 9999, true);

By specifing fill parameter you're telling the function to fit the image into given dimensions and then fill all unused space with color.

Whithout fill parameter this approach should work for most of the time, but will fail if someone upload an image that should be higher than 9999px.