1、jpg -> webp
1.1 使用 google 网页版工具 squoosh

1.2 使用命令行程序批量转换
1、官方下载工具包
2、使用 cwebp.exe 工具。由下面 bat 脚本运行:
@echo offsetlocal enabledelayedexpansion
rem 定义cwebp的路径,如果cwebp在系统路径中则不需要这行rem set cwebp_executable_path=D:\software\cwebp.exeset cwebp_executable_path=cwebp
rem 遍历当前目录下的所有.png文件for %%i in (*.png) do ( rem 构造输入和输出文件名 set input_file=%%~fi set output_file=!input_file:.png=.webp!
rem 执行cwebp命令 !cwebp_executable_path! -q 20 "%%~fi" -o "!output_file!")
echo All PNG files have been converted to WEBP.pause
2、webp -> 动态 webp
2.1、安装 Python
2.2、管理员运行 CMD
pip install imageio
2.3、py 代码
import reimport imageio.v2 as imageioimport globimport osfrom datetime import datetime
# 获取当前脚本所在的目录directory = os.path.dirname(os.path.abspath(__file__))
def natural_sort_key(s): return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)]
def exclude_timestamp_files(files): """排除形如'YYYYMMDDHH.webp'的文件""" timestamp_pattern = r'^\d{14}\.webp$' return [file for file in files if not re.match(timestamp_pattern, os.path.basename(file))]
# 获取目录下所有WebP文件的路径,并按自然顺序排序image_files = sorted(exclude_timestamp_files(glob.glob(os.path.join(directory, '*.webp'))), key=natural_sort_key)#image_files = sorted(glob.glob(os.path.join(directory, '*.webp')), key=natural_sort_key)
# 打印找到的WebP文件列表print(f'找到 {len(image_files)} 张 WebP 图片:')for image_file in image_files: print(image_file)print()
# 检查是否找到WebP文件if not image_files: raise ValueError(f"No WebP files found in directory: {directory}")
# 获取当前时间now = datetime.now()
# 格式化时间,精确到秒formatted_time = now.strftime('%Y%m%d%H%M%S')
# 输出的动图文件路径output_file = os.path.join(directory, f'{formatted_time}.webp')
# 读取图片并创建动图images = []for file in image_files: images.append(imageio.imread(file))
# 每秒3帧(每帧显示0.333秒)frame_duration = int(1000 / 3) # PILLOW-PIL expects duration in milliseconds
# 将图片保存为动图imageio.mimsave(output_file, images, format='WEBP', duration=frame_duration, loop=0, fps=3)
print(f'WebP动图已保存到 {output_file}')
3、mp4 -> 动态 webp
3.1、下载 ffmpeg
3.2、执行命令
# 整个转换ffmpeg -i D:\Media\test.mp4 -vf scale=360:-1 -r 10 -quality 20 -loop 0 -y D:\test_full.webp
#截取转换ffmpeg -ss 25 -t 5 -i D:\Media\test.mp4 -vf scale=360:-1 -r 10 -quality 20 -loop 0 -y D:\test.webp
-ss 25 # 这个选项告诉FFmpeg从源视频D:\Media\test.mp4的25秒处开始截取视频片段。-t 5 # 指定要截取的持续时间为5秒的视频片段。-i D:\Media\test.mp4 # 指定输入文件,这里是D:\Media\test.mp4。-vf scale=240:-1 # 这是视频滤镜(vf)选项,用于调整输出视频的尺寸。scale=240:-1意味着将视频的宽度调整为240像素,高度则按比例缩放以保持宽高比不变。-r 10 # 设置输出视频的帧率。这里设置为10帧/秒。-quality 20 # 这里使用了-quality参数来设置输出WebP动画的质量。-quality是FFmpeg中专门用于控制WebP输出质量的参数。数值范围通常在0到100之间,数值越小代表压缩越强,质量越低;数值越大,质量越好,但文件也更大。20是一个比较平衡的选择,可以产生相对较好的视觉效果同时保持较小的文件大小。-loop 0 # 指定输出的WebP动画应无限循环播放。0表示无限循环。-y # 强制覆盖输出文件,即使文件已经存在也不询问。