现在浏览器下载的图片都是webp格式, 有写使用图片的场景并不支持webp格式, 就很不方便, 在线使用转换图片的网站还要关注+收费, 所以就封装了一个方法,仅供参考
首先安装包
pip install pillow
下面是封装的类
from PIL import Image
import os
class ImageConverter:
def __init__(self, input_file):
"""
初始化时需要提供输入文件路径
"""
self.input_file = input_file
self.image = None
def load_image(self):
"""
加载输入的图片文件
"""
try:
self.image = Image.open(self.input_file)
print(f"Image {self.input_file} loaded successfully.")
except Exception as e:
print(f"Error loading image: {e}")
def convert(self, output_format):
"""
将图片转换为指定的格式并保存
:param output_format: 要转换的格式 (如 'png', 'jpeg', 'bmp', 'webp' 等)
"""
if self.image is None:
print("No image loaded. Please load an image first.")
return
# 提取文件名和目录
file_name, _ = os.path.splitext(self.input_file)
output_file = f"{file_name}.{output_format.lower()}"
try:
self.image.save(output_file, output_format.upper())
print(f"Image saved successfully as {output_file}.")
except Exception as e:
print(f"Error saving image: {e}")
def convert_to_all_formats(self, formats):
"""
将图片转换为多个指定格式并保存
:param formats: 需要转换的格式列表
"""
if self.image is None:
print("No image loaded. Please load an image first.")
return
for fmt in formats:
self.convert(fmt)
# 使用示例
if __name__ == "__main__":
# 输入图片文件路径
converter = ImageConverter("example.webp")
# 加载图片
converter.load_image()
# 转换为PNG格式
converter.convert("png")
# 转换为多个格式
converter.convert_to_all_formats(["jpeg", "bmp", "tiff", "webp"])