我创建了用于裁剪和调整图像大小的组件
这是代码(yii2)
组件使用imagine/imagine扩展,之前安装
<?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;
}
}
}
裁剪和调整大小的区别是:
- crop 无法显示所有图像,因此将裁剪边框(最适合不提供信息的缩略图)
- 调整大小显示完整图像,但边框将填充静态颜色(或透明,如果需要)(最好显示所有图像,如商店目录中所示)
静态使用这个组件,作为ServiceLocator的最佳实践