How to resize an image proportionally

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.

0 0
2 followers
Viewed: 12 371 times
Version: 2.0
Category: How-tos
Written by: AndroideLP
Last updated by: AndroideLP
Created on: Jun 5, 2017
Last updated: 11 months ago
Update Article

Revisions

View all history

Related Articles