2017-05-27 100 views
0

在一個個人項目中,我需要從一個使用php Imagine庫(http://imagine.readthedocs.io)實現ImageInterface(圖像)寬度和高度的對象獲得。Php想象一下獲取圖像的寬度和高度

,我需要解決的具體問題的方式,調整後的圖像保持原始寬高比,你可以在下面的類看到調整圖像大小:

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等etc庫,如:Get image height and width PHP而不是Imagine。

回答

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)); 
+1

問題是,我提供了一個最大寬度和高度的盒子,我想用長寬比來適應所提供的盒子。 –

+0

啊。那麼你需要做一些手動計算,我不認爲Imagine支持那個開箱即用的。 – rickdenhaan

+0

這就是我所做的;) –

相關問題