PHP Imagick::resampleImage resizes image instead of resampling

1k views Asked by At

I'm trying to downsample every image that I consider large for my site on uploading, so when a user tries to upload an image I firstly check if it has an acceptable resolution, otherwise I want to drop this resolution. The code I use for this is:

if ($image->isValid()){
    $imagick = new \Imagick(); 
    $imagick->readImage($image); 
    $resolution = $imagick->getImageResolution();
    $resolution_x = $resolution['x'];
    $resolution_y = $resolution['y'];
    if ($resolution_x > 30 && $resolution_y > 30){
        $imagick->setImageResolution($resolution_x,$resolution_x);
        $imagick->resampleImage($resolution_x/2,$resolution_x/2,\imagick::FILTER_CATROM,1);
    }
    $imagick->writeImage($uploadDir.$path); 
}

This code was supposed to set the resolution of an image with resolution 300 dpi for example to 150dpi. Instead of this, the resolution remains 300 dpi and the image dimensions drop to the half of their previous values (e.g an image (1200x800) turns into (600x400)). Am I missing something about the functionality of Imagick::resampleImage or is there any error in my code? I've done a lot of search before post this question and tried lot of different ways to succeed my goal using Imagick but I cannot get it done!

2

There are 2 answers

0
Danack On BEST ANSWER

The 'resolution' in the setImageResolution and getImageResolution functions refer to the dots per inch setting of the image, which is a hint to printers of what size to print the image i.e. how many dots per inch it should be printed at.

It does not affect the pixel dimensions of the image, and so does not have a noticeable effect on the image on a computer, which does not use the DPI setting to render an image.

You want to use either just $imagick->getImageWidth() and $imagick->getImageHeight() or $imagick->getImageGeometry() to get the pixel size of the image, and then resample it based on those pixel dimension, rather than the printer hint setting.

4
phansen On

It sounds like the resolution values should be the same in both setImageResolution and resampleImage. Have you tried this yet?

$imagick->setImageResolution($resolution_x/2,$resolution_x/2);