PHP中无法创建WebP图片缩略图,提示服务器GD函数不支持
WebP图片上传缩略图生成失败排查方案
问题重现
开发图片上传及缩略图生成功能时,除WebP格式外其余图片处理均正常,上传WebP图片时失败,报错:
"Your server does not support the GD function required to process this type of image"
用户代码如下:
$imagePrefix = time(); $imagename = "img_".$imagePrefix.trim($_FILES['file']['name']); $config['upload_path'] = 'uploads/nft/'; $config['allowed_types'] = 'jpg|jpeg|png|gif|PNG|JPG|JPEG|avif|webp'; $config['file_name'] = $imagename; $this->load->library('upload',$config); if($this->upload->do_upload('file')) { $uploadData = $this->upload->data(); $filename = $uploadData['file_name']; $datas=$_POST; $data = $this->upload->data(); $this->load->library('image_lib'); $config2['image_library'] = 'gd2'; $config2['source_image'] = $uploadData['full_path']; $config2['new_image'] = './uploads/nft/thumb/'.$uploadData["raw_name"].$uploadData['file_ext']; $config2['create_thumb'] = TRUE; $config2['maintain_ratio'] = FALSE; $config2['width'] = 350; $config2['height'] = 350; $this->image_lib->initialize($config2); $this->image_lib->clear(); }
问题原因
- 服务器GD库未启用WebP支持:GD2处理WebP依赖
imagecreatefromwebp()和imagewebp()两个核心函数,若服务器编译PHP时未加入WebP扩展,这两个函数不存在就会触发报错。 - CodeIgniter image_lib调用遗漏:原代码初始化image_lib后未调用
resize()方法,这是缩略图生成的关键步骤,同时旧版image_lib对WebP的适配逻辑可能不完善。
解决步骤
1. 验证服务器GD的WebP支持
创建测试脚本test_gd_webp.php,执行以下代码:
<?php var_dump(function_exists('imagecreatefromwebp')); var_dump(function_exists('imagewebp')); phpinfo(); ?>
- 若两个函数返回
true,说明GD支持WebP,问题出在CodeIgniter配置; - 若返回
false,需先开启服务器GD的WebP支持。
2. 开启GD的WebP支持
- Ubuntu/Debian服务器:
sudo apt-get install php-webp sudo systemctl restart apache2 # 或nginx,根据你的Web服务调整 - 编译PHP时添加支持:
重新编译PHP,配置参数加入:--with-webp
3. 调整CodeIgniter代码适配WebP
补全缩略图生成逻辑,并针对WebP做特殊处理:
if($this->upload->do_upload('file')) { $uploadData = $this->upload->data(); $filename = $uploadData['file_name']; $datas=$_POST; $data = $this->upload->data(); // 针对WebP格式单独处理 if($uploadData['file_ext'] === '.webp') { if(!function_exists('imagecreatefromwebp') || !function_exists('imagewebp')) { die("服务器不支持WebP图片处理"); } // 手动生成WebP缩略图 $source = imagecreatefromwebp($uploadData['full_path']); $thumb = imagecreatetruecolor(350, 350); imagecopyresampled($thumb, $source, 0, 0, 0, 0, 350, 350, imagesx($source), imagesy($source)); $thumbPath = './uploads/nft/thumb/'.$uploadData["raw_name"].$uploadData['file_ext']; imagewebp($thumb, $thumbPath); // 释放资源 imagedestroy($source); imagedestroy($thumb); } else { // 原有格式使用image_lib处理,补全resize()调用 $this->load->library('image_lib'); $config2['image_library'] = 'gd2'; $config2['source_image'] = $uploadData['full_path']; $config2['new_image'] = './uploads/nft/thumb/'.$uploadData["raw_name"].$uploadData['file_ext']; $config2['create_thumb'] = TRUE; $config2['maintain_ratio'] = FALSE; $config2['width'] = 350; $config2['height'] = 350; $this->image_lib->initialize($config2); $this->image_lib->resize(); $this->image_lib->clear(); } }
内容的提问来源于stack exchange,提问作者Ellyse
相关产品推荐
相关产品推荐

