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)
相关推荐
ascarl201019 分钟前
准确--k8s cgroup问题排查
java·开发语言
互联网杂货铺35 分钟前
完美搭建appium自动化环境
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
Gyoku Mint1 小时前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
fpcc1 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗1 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长1 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao2 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码2 小时前
STL解析——list的使用
开发语言·c++
SoFlu软件机器人2 小时前
智能生成完整 Java 后端架构,告别手动编写 ControllerServiceDao
java·开发语言·架构
英英_2 小时前
视频爬虫的Python库
开发语言·python·音视频