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)
相关推荐
孟健7 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞9 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽11 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程16 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪16 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook16 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python