I have created component to crop and resize images
here is the code (yii2)
Component uses imagine/imagine extension, install it before
<?php
namespace common\components;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Imagine\Image\ImageInterface;
use Imagine\Image\Point;
use Imagine\Imagick\Image;
class ResizeComponent
{
/**
* Resize image
* @param string $source source image path
* @param string $destination destination image path
* @param int $width
* @param int $height
* @param int $quality Jpeg sampling quality (0-100, 80 is best for seo)
* @return boolean is picture cropped
*/
public static function resizeImage($source, $destination, $width, $height, $quality = 80)
{
if (file_exists($source) && is_file($source)) {
$imagine = new Imagine();
$size = new Box($width, $height);
$mode = ImageInterface::THUMBNAIL_INSET;
$resizeimg = $imagine->open($source)->thumbnail($size, $mode);
$sizeR = $resizeimg->getSize();
$widthR = $sizeR->getWidth();
$heightR = $sizeR->getHeight();
$preserve = $imagine->create($size);
$startX = $startY = 0;
if ($widthR < $width) {
$startX = ($width - $widthR) / 2;
}
if ($heightR < $height) {
$startY = ($height - $heightR) / 2;
}
$preserve->paste($resizeimg, new Point($startX, $startY))
->save($destination, array('jpeg_quality' => $quality));
return true;
} else {
return false;
}
}
/**
* Crop image
* @param string $source source image path
* @param string $destination destination image path
* @param int $width
* @param int $height
* @param int $quality Jpeg sampling quality (0-100, 80 is best for seo)
* @return boolean is picture cropped
*/
public static function cropImage($source, $destination, $width, $height, $quality = 80)
{
if (file_exists($source) && is_file($source)) {
$imagine = new Imagine();
$size = new Box($width, $height);
$mode = ImageInterface::THUMBNAIL_OUTBOUND;
$image = $imagine->open($source)->thumbnail($size, $mode);
$image->thumbnail($size, $mode)->save($destination, array('jpeg_quality' => $quality));
return true;
} else {
return false;
}
}
}
The difference between crop and resize is :
- crop cant display all image, so borders will be cropped (best for not informative thumbnails)
- resize displays full image, but borders will be filled with static color (or transperency if needed) (best if all image needed to be shown, as in shop catalog)
Use this component statically, best practice as ServiceLocator