Python :AVIF 图片与其他图片格式间的批量转换

  图片格式 AVIF转换为常见的格式,比如 JPGPNG。本文介绍如何使用 Pillow 库实现AVIF与其他格式的相互转换。


环境配置

使用 Python 环境管理工具 `conda` 和常用库 `Pillow` 来处理图片格式转换。环境的详细信息:

安装步骤:

conda create -n yourenv python=3.8.19
conda activate yourenv

pip install pillow pillow-avif-plugin

Pillow 支持的常见图片格式:

  • JPEG (jpg, jpeg)
  • PNG
  • GIF
  • BMP
  • TIFF
  • WEBP
  • 其他格式(部分格式需要插件支持,如 AVIF

可以在 Pillow官方文档中查看支持的文件格式
也可以通过代码查看:

from PIL import Image

# 打印 Pillow 支持的文件格式
print(Image.registered_extensions())

1.将单个 AVIF 图片转换为 JPG 和 PNG

单张图片转换
将 `.avif` 图片转换为 `.jpg` 和 `.png` 格式。
import pillow_avif
from PIL import Image

# 将 AVIF 转换为 JPG
def convert_avif_to_jpg(input_path, output_path):
    with Image.open(input_path) as img:
        # 将图像转换为 RGB 模式确保兼容性
        img = img.convert('RGB')
        img.save(output_path, 'JPEG')

# 将 AVIF 转换为 PNG
def convert_avif_to_png(input_path, output_path):
    with Image.open(input_path) as img:
        img.save(output_path, 'PNG')

# 使用示例
convert_avif_to_jpg('demo.avif', 'output.jpg')
convert_avif_to_png('demo.avif', 'output.png')

运行效果:


2.批量转换目录下所有 AVIF 图片为其他格式

遍历一个目录下的所有 `.avif` 图片,批量转换为常见格式如 `JPG` 或 `PNG`。
import os
from PIL import Image
import pillow_avif


def convert_avif(input_path, output_path, output_format='jpg'):
    # 打开AVIF图像
    with Image.open(input_path) as img:
        # 如果输出格式是JPG,需要先转换为RGB模式
        if output_format.lower() in ['jpg', 'jpeg']:
            img = img.convert('RGB')
        # 处理其他格式直接保存
        img.save(output_path, output_format.upper())


def batch_convert_avif(input_directory, output_directory, output_format='jpg'):
    # 确保输出目录存在
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    # 遍历输入目录中的所有文件
    for filename in os.listdir(input_directory):
        if filename.lower().endswith('.avif'):
            input_path = os.path.join(input_directory, filename)
            output_filename = os.path.splitext(filename)[0] + f'.{output_format}'
            output_path = os.path.join(output_directory, output_filename)

            try:
                # 调用通用转换函数,指定输出格式
                convert_avif(input_path, output_path, output_format)
                print(f'已成功转换: {filename} -> {output_format.upper()}')
            except Exception as e:
                print(f'转换失败: {filename} 错误: {str(e)}')


# 使用示例:转换为PNG格式
batch_convert_avif('E:/software/test', 'E:/software/test', output_format='png')

运行效果:


3.将其他格式图片批量转换为 AVIF

将 `JPG` 或 `PNG` 等图片格式批量转换为 `AVIF`。
import os
from PIL import Image
import pillow_avif


def convert_to_avif(input_path, output_path):
    # 打开图片(支持JPG、PNG等格式)
    with Image.open(input_path) as img:
        # 如果不是RGBA或RGB模式,需要转换
        if img.mode not in ("RGBA", "RGB"):
            img = img.convert("RGBA")
        # 保存为AVIF格式
        img.save(output_path, "AVIF")


def batch_convert_to_avif(input_directory, output_directory, supported_formats=('jpg', 'jpeg', 'png')):
    # 确保输出目录存在
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    # 遍历输入目录中的所有文件
    for filename in os.listdir(input_directory):
        # 检查文件是否为支持的格式
        if filename.lower().endswith(supported_formats):
            input_path = os.path.join(input_directory, filename)
            # 修改输出文件扩展名为 .avif
            output_filename = os.path.splitext(filename)[0] + '.avif'
            output_path = os.path.join(output_directory, output_filename)

            try:
                # 将图片转换为AVIF
                convert_to_avif(input_path, output_path)
                print(f'已成功转换: {filename} -> {output_filename}')
            except Exception as e:
                # 捕获并处理异常
                print(f'转换失败: {filename} 错误: {str(e)}')


# 使用示例:将JPG、PNG批量转换为AVIF
batch_convert_to_avif('E:/software/test/avif', 'E:/software/test/avif')

运行效果:

希望这篇文章能帮助到你,如果有其他问题或建议,欢迎留言讨论!


刚刚好,看见你幸福的样子,于是幸福着你的幸福。 – 村上春树

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值