GD library and resize function

Hi,

I have a problem with resize function in GD library. My code which create thumbnail:

$thumbnail = new \Phalcon\Image\Adapter\GD($path);
$thumbnail->resize(300, 180)->save($pathThumbnail);

It doesn't create identical image(300, 180). It looks like this function only decreases image and if is it smaller image it doesn't increases to specified size in parameters.

What am I doing wrong?

Please, help me.

Regards, nansss

Post fixed. Please read the Markdown FAQ for properly formatting code.

edited Oct '15

Hey, i think you want to have resize while preserving aspect ratio of the thumbnail. If so, you can try with this helper function:

    function makeThumbnail($data)
    {
        $image = new \Phalcon\Image\Adapter\GD($data['path'] . $data['name']);
        $dimensions = explode('x', $data['size']);
        $new_width = $dimensions[0];
        $new_height = $dimensions[1];

        $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_width = (int) ($new_height * $source_aspect_ratio);
            $temp_height = $new_height;
        } 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($data['path'] . $data['size'] . '_' . $data['name']);
    }

Usage example:

        $data = array(
            'path' => 'PATH_TO_YOUR_IMAGE',
            'name' => 'samnpleimages.jpg',
            'size' => '300x180', 
        );
        $this->makeThumbnail($data);

This will produce thumbnail in same directory as original image with the name:

300x180_samnpleimages.jpg



1.1k

Could you tell me why should I do it with your code and why does it not work with my code?

Resize function resizes the image to either X or Y axis depending which is bigger. So if you have 1000x2000 image the thumbnail produced by your code will be 180px height and the width will be proportunally calculated but will not be 300.

My code calculates the aspect ratio so it doesnt stretch the image, centers the image in 300x180 canvas and crops whats outside.

You can try liquidRescale from the docs here https://docs.phalconphp.com/en/master/api/Phalcon%5Image%5Adapter%5GD.html but you need Imagick.