Php Imagine得到Image的宽度和高度

问题描述 投票:0回答:2

在个人项目中,我需要从一个使用php Imagine库(ImageInterface)实现http://imagine.readthedocs.io(图像)宽度和高度的对象。

我需要解决的具体问题是以调整大小的图像保持原始宽高比的方式调整图像大小,如下面的类所示:

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
    }
}

但是如何才能获得图像的宽度和高度?

我找到的所有解决方案都直接使用gd,imagick等库,例如:Get image height and width PHP而不是Imagine。

php image-size php-imagine
2个回答
1
投票

您可以使用getSize()方法:

/**
 * @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
}

虽然,如果你想用纵横比调整大小,你也可以使用scale()方法为BoxInterface获得新的测量结果而不必自己计算:

$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
投票

您可以使用缩略图功能上的“插入”模式缩放图像并保持其尺寸:

$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')
;
© www.soinside.com 2019 - 2024. All rights reserved.