PHP imagick扩展使用心得

/**
 * 图片缩放和裁剪,并进行存储
 * @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));


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值