新闻中心 网络推广 网站建设 优化推广 首页>新闻>网站建设

PB上传图片转换成webp功能开发

时间:2025-06-15   访问量:0

webp能将原图压缩30%左右还能保持清楚。所以正在被越来越多的人喜欢。

pb要增这个功能,第一步:找到ueditor中的Uploader.class.php,任意处添加函数。

   /**
 * 将图片转换为WebP格式
 */
private function convertToWebP()
{
    $originalFilePath = $this->filePath; // 保存原始文件路径
    $webpFilePath = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $this->filePath);
    $webpFullName = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $this->fullName);
    $webpFileName = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $this->fileName);

    if ($this->fileType === '.jpg' || $this->fileType === '.jpeg') {
        $image = imagecreatefromjpeg($this->filePath);
    } elseif ($this->fileType === '.png') {
        $image = imagecreatefrompng($this->filePath);
    } else {
        return false;
    }

    if ($image) {
        if (imagewebp($image, $webpFilePath)) {
            $this->filePath = $webpFilePath;
            $this->fullName = $webpFullName;
            $this->fileName = $webpFileName;
            $this->fileType = '.webp';
            $this->fileSize = filesize($webpFilePath);
            imagedestroy($image);
            unlink($originalFilePath); // 删除原始文件而不是WebP文件
            return true;
        }
        imagedestroy($image);
    }
    return false;
}

/**
 * 转换上传的图片为 WebP 格式(不影响原始文件)
 */


第二步:请找到如下代码(大概率出现在函数 handleFile()saveFile() 中):

找到:

$this->stateInfo = $this->stateMap[0];

后添加:

$this->convertToWebP(); // 上传成功后生成 .webp 副本

效果如:

$this->stateInfo = $this->stateMap[0];
$this->convertToWebP(); // 上传成功后生成 .webp 副本


第三步:funtion中的file.php中添加一个函数

// 添加一个新的函数用于转换图片为WebP格式
function convert_to_webp($src, $dest, $quality = 80)
{
    $info = getimagesize($src);
    $is_converted = false;
    switch ($info['mime']) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($src);
            $is_converted = imagewebp($image, $dest, $quality);
            imagedestroy($image);
            break;
        case 'image/gif':
            // 对于GIF文件,直接返回false,不进行WebP转换
            return false;
            break;
        case 'image/png':
            $image = imagecreatefrompng($src);
            $is_converted = imagewebp($image, $dest, $quality);
            imagedestroy($image);
            break;
        default:
            return false;
    }
    return $is_converted;
}


Ok了,我们现在来测试一下上传图片。下面的图片是我修改后上传的,点右键,查看源代码,可以看到图片已经转换成webp格式了。原图为1.07M,压缩后为:629KB


parade-3245208_1920.jpg


服务咨询
1对1咨询,专业客服为您解疑答惑
联系销售
15899750475
在线咨询
联系在线客服,为您解答所有的疑问
ARE YOU INTERESTED IN ?
感兴趣吗?

有关我们服务的更多信息,请联系项目经理

15899750475 杨先生