Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Imagick: How to resize without scaling up?

I am using PHP Imagick to manipulate images.

I have two use cases: "resize" and "crop".

In the "resize", if the original image's dimensions are less than the given width and the height, I do not want Imagick to scale it up and instead want it to simply return the original size.

However, as the PHP documentation says, the behavior of Imagick has been changed from version 3 (I am using version 6+) that it would always scale up the image.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

So, in my case, for given dimensions 400x400, an image of dimensions 200x150 should return an image of 200x150 not 400x300. For given dimensions 100x100 an image of dimensions 200x150 should return an image of 100x75 (that is scaling down should happen).

I tried thumbnailImage(), resizeImage() and scaleImage() without any luck. If I set bestfit to false it does the cropping, which is not what I want with resize.

Is there any way to get this done with Imagick?

like image 653
NexWarner Avatar asked Feb 10 '23 00:02

NexWarner


2 Answers

Try to do that way:

$max_width  = 1200;
$max_height = 800;
$im = new Imagick($path_to_image);
$im->resizeImage(
    min($im->getImageWidth(),  $max_width),
    min($im->getImageHeight(), $max_height),
    imagick::FILTER_CATROM,
    1,
    true
);
like image 187
Sergey Khalitov Avatar answered Feb 12 '23 13:02

Sergey Khalitov


Use this command:

convert input.img -resize 400x400\> output.img

Note the specific way of giving the wanted dimension with the appended \> modifier: it tells the conversion process to only resize images that are larger than 400x400 pixels. Images which are smaller stay un-touched.

like image 20
Kurt Pfeifle Avatar answered Feb 12 '23 14:02

Kurt Pfeifle