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)
相关推荐
fouryears_234171 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~2 小时前
C#---StopWatch类
开发语言·c#
lifallen3 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研3 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi4 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8244 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员4 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋4 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
cui__OaO5 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
鱼鱼说测试5 小时前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php