居中剪裁大致思路:

  1. 首先将图像进行缩放,使得缩放后的图像能够恰好覆盖裁减区域。(imagecopyresampled — 重采样拷贝部分图像并调整大小)
  2. 将缩放后的图像放置在裁减区域中间。(imagecopy — 拷贝图像的一部分)
  3. 裁减图像并保存。(imagejpeg | imagepng | imagegif — 输出图象到浏览器或文件)

    /**
     * 居中裁剪图片
     * @param string $source [原图路径]
     * @param int $target_w [设置宽度]
     * @param int $target_h [设置高度]
     * @param string $target [目标路径]
     * @return bool [裁剪结果]
     */
    private function imageCenterCrop($source, $target_w, $target_h, $target)
    {
        if (!function_exists('gd_info')) {
            $this->msg('gd库扩展未安装');
            return false;
        }

        if (!file_exists($source)) {
            $this->msg("文件不存在: {$source}");
            return false;
        }

        list($source_w, $source_h, $_type) = getimagesize($source);
        $this->msg("图片类型:{$_type},{$source}");

        /* 根据类型载入图像 */
        switch ($_type) {
            case IMAGETYPE_WEBP:
                $image = imagecreatefromwebp($source);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($source);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($source);
                break;
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($source);
                break;
            default:
                $this->msg("不支持的文件类型: {$source}");
                return false;
        }
        /* 计算裁剪宽度和高度 */
        $judge = (($source_w / $source_h) > ($target_w / $target_h));
        $resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w;
        $resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h;
        $start_x = $judge ? ($resize_w - $target_w) / 2 : 0;
        $start_y = !$judge ? ($resize_h - $target_h) / 2 : 0;
        /* 绘制居中缩放图像 */
        $resize_img = imagecreatetruecolor($resize_w, $resize_h);
        imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h);
        $target_img = imagecreatetruecolor($target_w, $target_h);
        imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h);
        /* 将图片保存至文件 */
        if (!is_resource($target)) {
            $_dir = dirname($target);
            if (!is_dir($_dir) && !@mkdir($_dir, 0777, true)) {
                $this->msg("创建目录失败:{$_dir}");
                return false;
            }
        }
        switch ($_type) {
            case IMAGETYPE_WEBP:
                imagewebp($target_img, $target);
                break;
            case IMAGETYPE_JPEG:
                imagejpeg($target_img, $target);
                break;
            case IMAGETYPE_PNG:
                imagepng($target_img, $target);
                break;
            case IMAGETYPE_GIF:
                imagegif($target_img, $target);
                break;
        }
        return boolval(file_exists($target));
    }

标签: none

添加新评论