/**
* 图片缩放和裁剪,并进行存储
* @param string $srcPath 图片源地址
* @param string $dstPath 目标存储地址
* @param int $thumbWidth 缩略图宽度
* @param array $crop 裁剪尺寸
* @return string $err 错误信息
*/
function create_thumb($srcPath, $dstPath, $thumbWidth, $crop = array()){
$err = '';
try{
$im = new Imagick($srcPath);
$im->setimageformat('png');
$im->stripimage();
$oriWidth = $im->getimagewidth();
$oriHeight = $im->getimageheight();
$quotient = $oriWidth / $oriHeight;
$thumbHeight = $thumbWidth / $quotient;
if ($oriWidth > $thumbWidth) {
$im->resizeimage($thumbWidth, $thumbHeight, Imagick::FILTER_LANCZOS, 1, false);
}
if (!empty($crop)) {
$currentWidth = $im->getimagewidth();
$currentHeight = $im->getimageheight();
$scale = $crop['width'] / $crop['height'];
if ($quotient === $scale) {
$im->resizeimage($crop['width'], $crop['height'], Imagick::FILTER_LANCZOS, 1, false);
} elseif ($quotient > $scale) {
$cutWidth = $currentHeight * $scale;
$im->cropimage($cutWidth, $currentHeight, $currentWidth/4, 0);
$im->resizeimage($crop['width'], $crop['height'], Imagick::FILTER_LANCZOS, 1, false);
} elseif ($quotient < $scale) {
$cutHeight = $currentWidth / $scale;
$im->cropimage($currentWidth, $cutHeight, 0, 0);
$im->resizeimage($crop['width'], $crop['height'], Imagick::FILTER_LANCZOS, 1, false);
}
}
$im->writeimage($dstPath);
$im->destroy();
}catch (ImagickException $e){
$err = $e->getMessage();
}
return $err;
}
例如你想把一张图片缩放到480宽,并裁剪成一个192*192的正方形,可以这样调用:
create_thumb('c:/test.png', 'd:/test.png', 480, array('width'=>192, 'height'=>192));