/**
     * 图片裁剪,以图片中心为中心裁切任意尺寸的图片
     * 裁剪规则:
     *      1. 高度为空或为零   按宽度缩放 高度自适应
     *      2. 宽度为空或为零  按高度缩放 宽度自适应
     *      3. 宽度,高度到不为空或为零  按宽高比例等比例缩放裁剪  默认从头部居中裁剪
     * @param number $width
     * @param number $height
     */
    public function resize_new($path)
    {
        $image = new Imagick($path);

        $size = $image->getImagePage();
        //原始宽高
        $src_width = $size ['width'];
        $src_height = $size ['height'];

        if ($src_width > $src_height) {
            $width = $src_height;
            $height = $src_height;
        }

        if ($src_width <= $src_height) {
            $width = $src_width;
            $height = $src_width;
        }
        //按宽度缩放 高度自适应
        if ($width != 0 && $height == 0) {
            if ($src_width > $width) {
                $height = intval($width * $src_height / $src_width);

                if ($this->type == 'gif') {
                    $this->_resizeGif($width, $height);
                } else {
                    $image->thumbnailImage($width, $height, true);
                }
            }
            return;
        }
        //按高度缩放 宽度自适应
        if ($width == 0 && $height != 0) {
            if ($src_height > $height) {
                $width = intval($src_width * $height / $src_height);

                if ($this->type == 'gif') {
                    $this->_resizeGif($width, $height);
                } else {
                    $image->thumbnailImage($width, $height, true);
                }
            }
            return;
        }

        //缩放后裁剪的位置
        $crop_x = 0;
        $crop_y = 0;

        // 宽高比例
        $o_s = bcdiv($src_width, $src_height, 5);
        $s = bcdiv($width, $height, 5);

        // 缩放之后的宽高
        $s_w = $width;
        $s_h = $height;

        if ($o_s < $s) {
            $s_h = 0;
        } else {
            $s_w = 0;
        }
        $image->resizeImage($s_w, $s_h, Imagick::FILTER_CATROM, 1);
        $scaleImage = $image->getImagePage();

        $crop_x = ($scaleImage['width'] - $width) / 2;
        $crop_y = ($scaleImage['height'] - $height) / 2;
        $image->cropImage($width, $height, $crop_x, $crop_y);
        $image->writeImage($path);
    }
最后修改:2020 年 10 月 14 日
如果觉得我的文章对你有用,请随意赞赏