Yii 2.0: How to resize an image proportionally

1 follower

Using the imagine extension is very simple Create this in your component:

/**     * @author André Luiz Pereira
     * @param string $ pathtoimage image the relative path: to/path/image.jpg
     * @param int $width – max width to resize 
     * @param int $height – max height to resize
     * @param int $quality – Image quality default 80
     * @return void
     */
    public function ImageProporcional($pathtoimage, $width, $height, $quality = 80) {
        $pathConstruct = \yii\helpers\Url::to('@webroot/' . $pathtoimage);
        $imagem = \yii\imagine\Image::getImagine();
        $getimg = $imagem->open($pathConstruct);
        $size = new \Imagine\Image\Box($width, $height);
      // We created the thumbnail with the data defined in the box
        $resizeimg = $getimg->thumbnail($size, \Imagine\Image\ImageInterface::THUMBNAIL_INSET);
       // Get real size
        $sizeR = $resizeimg->getSize();
        $widthR = $sizeR->getWidth();
        $heightR = $sizeR->getHeight();
        $preserve = $imagem->create($size);
 
        $startX = $startY = 0;
if ($widthR < $width) {
            $startX = ( $width - $widthR ) / 2;
        }
 
        if ($heightR < $height) {
            $startY = ( $height - $heightR ) / 2;
        }
        $preserve->paste($resizeimg, new \Imagine\Image\Point($startX, $startY))->save($pathConstruct, ['quality' => $quality]);
 
    }

This simple code resizes and modifies image quality in the $pathtoimage variable, $width and $ height being the maximum values, resizing is only applied if the actual image size is larger than the size defined in the method "ImageProportional"

Follow the example criação de sites.

Seguir Facebook.

Total 1 comment

#20086 report it
AndroideLP at 2017/06/06 10:43am
Critics and suggestions

For reviews and suggestions use the comments so I can improve the posts.

Leave a comment

Please to leave your comment.

Write new article