以下是一段python 代码,可以用来将特定文件夹内的图片压缩成webp 格式
使用前请确保安装过os和PIL包
import os
from PIL import Image
# 手动指定参数和路径
INPUT_FOLDER = "." # 图片所在的文件夹路径,当前目录用"."表示
QUALITY_LEVEL = 80 # WebP 压缩质量 (1-100, 数值越高质量越好)
def compress_to_webp(input_folder, quality=80):
"""
Compresses all images in the input folder to WebP format and removes the original files.
Args:
input_folder (str): Path to the folder containing images to compress
quality (int): Quality level for WebP compression (1-100, higher is better quality)
"""
# Supported image formats
supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif', '.gif')
# Get all image files in the folder
image_files = []
for filename in os.listdir(input_folder):
if filename.lower().endswith(supported_formats):
image_files.append(filename)
print(f"Found {len(image_files)} images to convert...")
for filename in image_files:
input_path = os.path.join(input_folder, filename)
# Create output path with .webp extension
base_name = os.path.splitext(filename)[0]
output_path = os.path.join(input_folder, f"{base_name}.webp")
try:
# Open and compress the image
with Image.open(input_path) as img:
# Convert RGBA to RGB if necessary (for compatibility)
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# Save as WebP with specified quality
img.save(output_path, "WEBP", quality=quality, optimize=True)
# Remove the original file after successful conversion
os.remove(input_path)
print(f"Compressed and converted: {filename} -> {base_name}.webp")
except Exception as e:
print(f"Error processing {filename}: {str(e)}")
print("Compression completed!")
def main():
# 检查指定的文件夹是否存在
if not os.path.isdir(INPUT_FOLDER):
print(f"Error: {INPUT_FOLDER} is not a valid directory")
return
compress_to_webp(INPUT_FOLDER, QUALITY_LEVEL)
if __name__ == "__main__":
main()
