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)
相关推荐
躺平的花卷19 分钟前
Python爬虫案例六:抓取某个地区某月份天气数据并保存到mysql数据库中
数据库·爬虫·python·mysql
虚拟搬运工21 分钟前
Python类及元类的创建流程
开发语言·chrome·python
消失的旧时光-194340 分钟前
kotlin的密封类
android·开发语言·kotlin
A_cot44 分钟前
Redis 的三个并发问题及解决方案(面试题)
java·开发语言·数据库·redis·mybatis
学步_技术44 分钟前
Python编码系列—Python原型模式:深克隆与高效复制的艺术
开发语言·python·原型模式
alden_ygq1 小时前
GCP容器镜像仓库使用
java·开发语言
Desire.9841 小时前
Python 数学建模——灰色关联度分析
python·数学建模·灰色关联度
苹果酱05671 小时前
一文读懂SpringCLoud
java·开发语言·spring boot·后端·中间件
Eoneanyna1 小时前
QT设置git仓库
开发语言·git·qt
小鹿( ﹡ˆoˆ﹡ )1 小时前
Python中的树与图:构建复杂数据结构的艺术
开发语言·python