python 图片类型转为 jpg

问题

Windows照片查看器无法显示此图片,因为计算机上的可用内存可能不足...

做法:

把一个文件夹全部的图片(比如 webm, jiff, bpm, avif 等等),都转为 jpg, 然后写入到一个新的文件夹,保存放到桌面。

最常见的一个情况是, 使用 Alt + PrintScreen(PS) 进行截图之后,文件会非常大,需要清除图片中的一些无用信息。

python3 复制代码
import os
import uuid
from PIL import Image

# 下面这一行,实际上使用了!
# 目的是为了能读取 .avif 类型的图片
import pillow_avif # pip install pillow-avif-plugin
# https://stackoverflow.com/questions/74527775/how-to-convert-avif-to-png-with-python


# 把全部的图片,都转为 jpg, 然后保存到桌面
def convert_image_to_jpg(source="./", output_suffix="jpg"):
    output_dir = r"C:\Users\Administrator\Desktop\temp_images_" + str(uuid.uuid4())
    os.makedirs(output_dir, exist_ok=True)

    # 1. source is a folder
    if os.path.isdir(source):
        print("source is a dir: ", source)

        for img_name in os.listdir(source):
            # 1. 输入文件名
            img_path = os.path.join(source, img_name)
            print("output_name: ", img_path)

            # 2. 输出文件名
            prefix, suffix = os.path.splitext(img_name)
            output_name = os.path.join(output_dir, f"{prefix}.{output_suffix}")
            print("output_name:", output_name)

            # 3. 文件类型转换
            im = Image.open(img_path)
            rgb_im = im.convert('RGB')  # OSError: cannot write mode RGBA as JPEG
            rgb_im.save(output_name)
            print()

    # 2. source is a single image
    else:
        print("source is a file: ", source)
        prefix, suffix = os.path.splitext(source)
        out_name = os.path.join(prefix, output_suffix)
        im = Image.open(source)
        im.save(out_name)
    print("Done")


# 传入文件夹地址, 输出: 默认保存到桌面
p = r"C:\Users\Administrator\Desktop\imgs\"
convert_image_to_jpg(p)
相关推荐
数据智能老司机5 分钟前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i3 小时前
django中的FBV 和 CBV
python·django
c8i3 小时前
python中的闭包和装饰器
python
这里有鱼汤6 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩16 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在21 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法