You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用PHP上传图片前对图片进行尺寸调整?

嘿,我来帮你把这个图片Resize类完善成支持上传优化的版本!你已经有了基础的图片打开和尺寸获取功能,咱们可以加上压缩、格式转换、冗余信息清理这些实用的优化特性,让上传的图片体积更小还能保证画质。

完善后的图片优化Resize类
<?php
class Resize {
    // *** 类变量
    private $image;
    private $width;
    private $height;
    private $imageResized;
    private $quality = 80; // 默认压缩质量(1-100,越高画质越好体积越大)
    private $targetFormat = 'jpeg'; // 默认输出格式,推荐用webp更省体积

    function __construct($fileName) {
        // *** 打开目标图片
        $this->image = $this->openImage($fileName);
        // *** 获取原图宽高
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
    }

    // 兼容多格式的图片打开方法
    private function openImage($fileName) {
        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        switch($extension) {
            case 'jpg':
            case 'jpeg':
                $img = imagecreatefromjpeg($fileName);
                break;
            case 'png':
                $img = imagecreatefrompng($fileName);
                // 保留PNG图片的透明度
                imagealphablending($img, true);
                imagesavealpha($img, true);
                break;
            case 'gif':
                $img = imagecreatefromgif($fileName);
                break;
            case 'webp':
                $img = imagecreatefromwebp($fileName);
                break;
            default:
                throw new Exception("不支持的图片格式: {$extension}");
        }
        return $img;
    }

    // 按目标宽度等比例缩放
    public function resizeToWidth($targetWidth) {
        $ratio = $targetWidth / $this->width;
        $targetHeight = $this->height * $ratio;
        $this->resizeImage($targetWidth, $targetHeight);
    }

    // 按目标高度等比例缩放
    public function resizeToHeight($targetHeight) {
        $ratio = $targetHeight / $this->height;
        $targetWidth = $this->width * $ratio;
        $this->resizeImage($targetWidth, $targetHeight);
    }

    // 按最大宽高限制缩放(适合网页图片,避免过大)
    public function resizeToMax($maxWidth, $maxHeight) {
        $widthRatio = $maxWidth / $this->width;
        $heightRatio = $maxHeight / $this->height;
        $ratio = min($widthRatio, $heightRatio);
        $targetWidth = $this->width * $ratio;
        $targetHeight = $this->height * $ratio;
        $this->resizeImage($targetWidth, $targetHeight);
    }

    // 实际执行缩放的核心方法
    private function resizeImage($targetWidth, $targetHeight) {
        // 创建新的画布
        $this->imageResized = imagecreatetruecolor($targetWidth, $targetHeight);
        
        // 处理PNG/GIF的透明度,避免出现黑边
        $sourceExt = strtolower(pathinfo($this->image, PATHINFO_EXTENSION));
        if($sourceExt === 'png' || $sourceExt === 'gif') {
            imagealphablending($this->imageResized, false);
            imagesavealpha($this->imageResized, true);
            $transparent = imagecolorallocatealpha($this->imageResized, 255, 255, 255, 127);
            imagefilledrectangle($this->imageResized, 0, 0, $targetWidth, $targetHeight, $transparent);
        }

        // 执行高质量缩放
        imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $targetWidth, $targetHeight, $this->width, $this->height);
    }

    // 设置自定义压缩质量
    public function setQuality($quality) {
        $this->quality = max(1, min(100, $quality));
    }

    // 设置目标输出格式(支持jpeg/png/webp)
    public function setTargetFormat($format) {
        $allowedFormats = ['jpeg', 'png', 'webp'];
        if(in_array(strtolower($format), $allowedFormats)) {
            $this->targetFormat = strtolower($format);
        }
    }

    // 保存优化后的图片
    public function saveImage($savePath, $override = true) {
        // 自动创建目录(如果不存在)
        if(!is_writable(dirname($savePath)) && !mkdir(dirname($savePath), 0755, true)) {
            throw new Exception("无法写入目标路径: {$savePath}");
        }

        // 根据目标格式保存图片,自动适配压缩参数
        switch($this->targetFormat) {
            case 'jpeg':
                imagejpeg($this->imageResized, $savePath, $this->quality);
                break;
            case 'png':
                // PNG的quality参数是压缩级别(0-9),这里做一下转换
                $pngQuality = floor(($this->quality / 100) * 9);
                imagepng($this->imageResized, $savePath, $pngQuality);
                break;
            case 'webp':
                imagewebp($this->imageResized, $savePath, $this->quality);
                break;
        }

        // 释放内存,避免资源泄漏
        imagedestroy($this->image);
        imagedestroy($this->imageResized);
    }
}
?>
上传时的使用示例
// 处理前端上传的图片(假设表单字段名为image)
if(isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $tempFile = $_FILES['image']['tmp_name'];
    $uploadDir = 'uploads/';
    // 用唯一ID作为文件名,避免重复
    $fileName = uniqid() . '.webp';
    $savePath = $uploadDir . $fileName;

    try {
        // 初始化Resize类
        $resize = new Resize($tempFile);
        // 设置最大宽高为1920px(适合网页展示)
        $resize->resizeToMax(1920, 1920);
        // 设置压缩质量为75(平衡画质和体积)
        $resize->setQuality(75);
        // 输出为webp格式(比jpeg小30%左右)
        $resize->setTargetFormat('webp');
        // 保存优化后的图片
        $resize->saveImage($savePath);

        echo "图片上传优化完成!路径:{$savePath}";
    } catch(Exception $e) {
        echo "错误:{$e->getMessage()}";
    }
}
核心优化点说明
  • WebP格式转换:WebP是谷歌推出的高效格式,比JPEG/PNG体积小25%-50%,现在主流浏览器都支持。
  • 高质量缩放:使用imagecopyresampled而非imagecopyresized,缩放后的图片更清晰。
  • 透明度保留:处理PNG/GIF时自动保留透明通道,避免出现黑边。
  • 冗余信息清理:重新生成的图片会自动去除原图片的EXIF、IPTC等冗余数据,进一步减小体积。
  • 可配置的压缩质量:可以根据场景灵活调整,比如缩略图用60-70,详情图用80-90。

内容的提问来源于stack exchange,提问作者user7425848

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:39:35