Crop to Fit Image With GD


Nov '14

Jan '15

2

1507

2

I was trying to find out how to crop-to-fit an image with GD. But there were no examples with Phalcon. There was one post that mentioned using Imagick. The only problem was that you needed to compiled Imagick with --lrf in order to use liquidRescale. This may not be an option on many hosting platforms. For that reason, I wanted to use GD instead.

I found this post after a quick Google search. It helped me create the base for my Phalcon version of the function. This may seem pretty easy for some people, but I found enough people asking, that I figured I would share the whole code.

function resizeImage($source, $dest, $new_width, $new_height, $quality)
{
    // Taken from http://salman-w.blogspot.com/2009/04/crop-to-fit-image-using-aspphp.html
    $image = new Phalcon\Image\Adapter\GD($source);
    $source_height = $image->getHeight();
    $source_width = $image->getWidth();
    $source_aspect_ratio = $source_width / $source_height;
    $desired_aspect_ratio = $new_width / $new_height;
    if ($source_aspect_ratio > $desired_aspect_ratio) {
        $temp_height = $new_height;
        $temp_width = ( int ) ($new_height * $source_aspect_ratio);
    } else {
        $temp_width = $new_width;
        $temp_height = ( int ) ($new_width / $source_aspect_ratio);
    }
    $x0 = ($temp_width - $new_width) / 2;
    $y0 = ($temp_height - $new_height) / 2;
    $image->resize($temp_width, $temp_height)->crop($new_width, $new_height, $x0, $y0);
    $image->save($dest, $quality);
}

If you really wanted to use Imagick, then you could just replace GD in the constructor (Phalcon\Image\Adapter\Imagick($source)) and it should work fine. This way you don't need to compile Imagick from source in order to get liquidRescale.


Nhi
5.3k

Hey @James

nice tip, so i have a question. if i don't install extension images php it woking ?

GD comes with PHP. There should be nothing to install or setup, unless for some reason GD was disabled.

If you wanted to use Imagick, just replace the call to the image adapter.