[英]Php Imagine get Image's width and height
在個人項目中,我需要從使用php Imagine庫( http://imagine.readthedocs.io )實現ImageInterface
(圖像)寬度和高度的對象獲得。
我需要解決的特定問題是調整圖像的大小,使調整后的圖像保持原始的寬高比,如您在以下課程中看到的那樣:
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等庫,例如: 獲取圖像高度和寬度PHP,而不是Imagine。
您可以為此使用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
}
雖然,如果您想使用寬高比調整大小,也可以對BoxInterface
使用scale()
方法來獲取新的度量值,而不必自己計算:
$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));
您可以使用縮略圖功能上的插入模式縮放圖像並保持其尺寸:
$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')
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.