Php Imagine get Image's width and height

2k views Asked by At

On a personal project I need to get from an object that Implements a ImageInterface (the image) the width and height using the php Imagine library (http://imagine.readthedocs.io).

The specific problem that I need to solve is to resize an Image in a way that the resized image maintains the original Aspect Ratio as you can see in the following class:

namespace PcMagas\AppImageBundle\Filters\Resize;

use PcMagas\AppImageBundle\Filters\AbstractFilter;
use Imagine\Image\ImageInterface;
use PcMagas\AppImageBundle\Filters\ParamInterface;
use PcMagas\AppImageBundle\Exceptions\IncorectImageProssesingParamsException;

class ResizeToLimitsKeepintAspectRatio extends AbstractFilter
{
    public function apply(ImageInterface $image, ParamInterface $p) 
    {
        /**
         * @var ResizeParams $p
         */
        if(! $p instanceof ResizeParams){
            throw new IncorectImageProssesingParamsException(ResizeParams::class);
        }

        /**
         * @var float $imageAspectRatio
         */
        $imageAspectRatio=$this->calculateImageAspectRatio($image);



    }

    /**
     * @param ImageInterface $image
     * @return float
     */
    private function calculateImageAspectRatio(ImageInterface $image)
    {
        //Calculate the Image's Aspect Ratio
    }
}

But how can I get the image's width and height?

All the solutions I found are using directly the gd, imagick etc etc library such as: Get image height and width PHP and not the Imagine one.

2

There are 2 answers

5
rickdenhaan On

You can use the getSize() method for that:

/**
 * @param ImageInterface $image
 * @return float
 */
private function calculateImageAspectRatio(ImageInterface $image)
{
    //Calculate the Image's Aspect Ratio
    $size = $image->getSize(); // returns a BoxInterface

    $width = $size->getWidth();
    $height = $size->getHeight();

    return $width / $height; // or $height / $width, depending on your usage
}

Although, if you want to resize with aspect ratio, you can also use the scale() method for the BoxInterface to get the new measurements without having to calculate that yourself:

$size = $image->getSize();

$width = $size->getWidth();    // 640
$height = $size->getHeight();  // 480

$size->scale(1.25); // increase 25%

$width = $size->getWidth();    // 800
$height = $size->getHeight();  // 600

// or, as a quick example to scale an image up by 25% immediately:
$image->resize($image->getSize()->scale(1.25));
0
Alexander Schranz On

You can scale a image and keep its dimension by using the Inset mode on the thumbnail function:

$size = new Imagine\Image\Box(40, 40);

$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;

$imagine->open('/path/to/large_image.jpg')
    ->thumbnail($size, $mode)
    ->save('/path/to/thumbnail.png')
;