如何将图片转换为 WebP 格式
← 返回博客
如何将图片转换为 WebP 格式
· 5 分钟阅读
选择正确的 WebP 转换模式
将图片转换为 WebP 时,首先需要决定使用有损(lossy)还是无损(lossless)模式。如果原图是 JPG(已经是有损格式),应该使用有损 WebP;如果原图是 PNG(无损格式,特别是带透明背景的),通常应该使用无损 WebP 以保留透明度和图形精度;对于包含透明背景的图形(Logo、图标),也使用无损 WebP。
有损 WebP 的质量参数范围是 0–100,与 JPG 类似。推荐的起点是质量 75–80,这通常能在视觉质量和文件大小之间取得最佳平衡,比相同质量的 JPG 小约 30%。对于需要高质量输出的产品图,可以使用 85–90。
使用在线工具转换
使用我们的在线图片转换工具转为 WebP 的步骤:(1)打开图片转换工具,上传 JPG 或 PNG 图片;(2)在输出格式选项中选择 WebP;(3)选择有损或无损模式,设置质量参数(有损模式);(4)点击转换并下载 .webp 文件。工具在浏览器中本地处理,不上传到服务器,支持拖放上传,通常支持 PNG、JPG、GIF、BMP 等输入格式。
使用 cwebp 命令行工具
# 安装 libwebp 工具集 / Install libwebp tools
# macOS: brew install webp
# Ubuntu/Debian: sudo apt install webp
# 有损转换(推荐质量 75-85)
# Lossy conversion (recommended quality 75-85)
cwebp -q 80 photo.jpg -o photo.webp
# 无损转换(适合 PNG)
# Lossless conversion (suitable for PNG)
cwebp -lossless icon.png -o icon.webp
# 保留 EXIF 元数据
# Preserve EXIF metadata
cwebp -q 80 -metadata exif photo.jpg -o photo.webp
# 批量转换所有 JPG
# Batch convert all JPGs
for f in *.jpg; do
cwebp -q 80 "$f" -o "${f%.jpg}.webp"
done
# 查看转换结果信息
# View conversion result info
webpinfo photo.webp
在 Python 中转换为 WebP
from PIL import Image
import os
from pathlib import Path
def convert_to_webp(input_path, output_path=None, quality=80, lossless=False):
"""
将图片转换为 WebP 格式
Convert image to WebP format
"""
input_path = Path(input_path)
if output_path is None:
output_path = input_path.with_suffix('.webp')
with Image.open(input_path) as img:
original_size = input_path.stat().st_size
# 对于 RGBA 图片,保留透明度 / For RGBA images, preserve transparency
if img.mode == 'RGBA' or lossless:
img.save(str(output_path), 'WEBP', lossless=True, quality=100)
else:
if img.mode != 'RGB':
img = img.convert('RGB')
img.save(str(output_path), 'WEBP', quality=quality)
new_size = Path(output_path).stat().st_size
reduction = (1 - new_size / original_size) * 100
print(f"{input_path.name}: {original_size//1024}KB → {new_size//1024}KB ({reduction:.1f}% smaller)")
# 批量转换目录 / Batch convert directory
def batch_convert(directory, quality=80):
for ext in ['*.jpg', '*.jpeg', '*.png']:
for f in Path(directory).glob(ext):
convert_to_webp(f, quality=quality)
batch_convert('./images', quality=80)
在 Node.js 中使用 Sharp 转换
// 安装 / Install: npm install sharp
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
// 单文件转换 / Single file conversion
async function toWebP(inputPath, quality = 80) {
const outputPath = inputPath.replace(/\.(jpg|jpeg|png|gif)$/i, '.webp');
const info = await sharp(inputPath)
.webp({ quality, lossless: false })
.toFile(outputPath);
console.log(`Converted: ${info.size} bytes → ${outputPath}`);
return outputPath;
}
// 批量转换 / Batch conversion
async function batchToWebP(dir, quality = 80) {
const files = fs.readdirSync(dir).filter(f => /\.(jpg|jpeg|png)$/i.test(f));
let totalSaved = 0;
for (const file of files) {
const inputPath = path.join(dir, file);
const outputPath = await toWebP(inputPath, quality);
const origSize = fs.statSync(inputPath).size;
const newSize = fs.statSync(outputPath).size;
totalSaved += origSize - newSize;
}
console.log(`Total saved: ${(totalSaved / 1024 / 1024).toFixed(2)} MB`);
}
batchToWebP('./public/images', 80);
在 Nginx 中自动提供 WebP
在生产服务器上,可以配置 Nginx 自动检测浏览器是否支持 WebP,然后提供 WebP 版本或回退到原格式。这需要同时保存 WebP 版本和原始版本,由服务器根据 Accept 头部智能选择。
# Nginx 配置 WebP 自动服务 / Nginx config for automatic WebP serving
map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}
server {
location ~* \.(jpg|jpeg|png)$ {
add_header Vary Accept;
try_files $uri$webp_suffix $uri =404;
}
}
转换质量验证
转换完成后,应验证 WebP 图片的质量是否符合要求。最直接的方法是在浏览器中并排比较原图和 WebP 版本,100% 缩放检查细节区域。还可以使用 SSIM(结构相似性指数)等客观指标来量化质量差异:SSIM 值大于 0.95 通常意味着视觉上几乎无法区分的质量。
对于重要的产品图或营销图,建议让团队成员进行视觉质量审查,特别是检查产品细节、文字清晰度和颜色准确性。一旦确认了质量可接受的最低质量参数(如 75),就可以放心地对所有同类图片使用相同设置进行批量转换。
在 Next.js 和现代框架中使用 WebP
现代前端框架对 WebP 提供了良好支持。Next.js 的 组件会自动将图片转换并提供 WebP(或 AVIF)版本,无需手动转换。只需使用 Next.js 的 Image 组件替代普通的 img 标签,框架会自动处理格式转换、懒加载、响应式尺寸等所有优化。
立即尝试在线工具,无需安装,免费使用。
打开工具 →
立即免费使用相关工具
免费使用 →