使用python 实现图片的各种格式转换,保存到本地

现在浏览器下载的图片都是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"])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值