Search code examples
phpimagezend-framework2php-imagine

Imagine with ZF2: Ratio Resize


I am working with the Imagine library in Zend Framework 2: Imagine

What I want too do is make some pictures as thumbnails for my picture page, too make it load faster. But the problem is that I don't know how to resize with ratio in the library.

Does somebody knows how you can resize with ratio. So I want to say that the picture is 300 width and it will automatic calculate the height.

This is my code at this moment:

public function resizeImage($photo , $width, $height)
{
    $sm = $this->getServiceLocator();
    $imagine = $sm->get('image_service');
    $image = $imagine->open('public/img/gallery/album1/thumbnails/klj1.jpg');
    $image->resize(new Box($width, $height));
    $image->save('public/img/gallery/album1/thumbnails/klj1-thumb.jpg');
}

Solution

  • I am using the following calculation to calculate the ratio:

    $size = $image->getSize();
    if ($height < $width)
    {
        $divider = $size->getWidth() / $width;
        $calcHeight = $size->getHeight() / $divider;
        $calcWidth = $width;
    } else {
        $divider = $size->getHeight() / $height;
        $calcWidth = $size->getWidth() / $divider;
        $calcHeight = $height;
    }    
    $image->resize(new Box($calcWidth, $calcHeight));