You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的PIL库处理图像时显示进度?

实现PIL保存大图片时的进度显示

PIL的save方法本身没有内置进度回调机制,要实现0.0到1.0的数值进度提示,可以通过自定义带进度监控的文件写入类来实现,核心思路是监控写入文件的字节数,结合图片的预估总大小计算实时进度。

实现步骤

  • 自定义一个继承自io.BufferedWriter的类,重写write方法,每次写入时更新并输出进度。
  • 预估图片保存后的总大小(两种可选方式):
    1. 先将图片写入BytesIO获取准确总大小(适合内存足够的场景)
    2. 通过图片像素数据量结合质量参数估算(内存友好,适合超大图片)

完整代码示例

from PIL import Image
import io
import sys

class ProgressWriter(io.BufferedWriter):
    def __init__(self, raw, total_size):
        super().__init__(raw)
        self.total_size = total_size
        self.written = 0

    def write(self, b):
        self.written += len(b)
        progress = self.written / self.total_size
        # 输出进度,覆盖当前行(避免刷屏)
        sys.stdout.write(f"\r保存进度: {progress:.2f}")
        sys.stdout.flush()
        return super().write(b)

# 打开并处理图片
image = Image.open('wallpaper.png')
# 这里添加你的图片修改逻辑
# image = image.resize((1920, 1080)) 示例修改操作

# 方式1:先写入BytesIO获取准确总大小(适合内存充足的情况)
with io.BytesIO() as temp_buffer:
    image.save(temp_buffer, format='PNG', quality=85)
    total_size = temp_buffer.tell()

# 方式2:通过像素数据估算(内存友好,适合超大图片)
# total_size = image.width * image.height * len(image.getbands()) * 0.15  # 0.15是PNG质量85的大致压缩比,可根据实际调整

# 使用带进度的Writer保存图片
with open('modified_wallpaper.png', 'wb') as f:
    progress_writer = ProgressWriter(f, total_size)
    image.save(progress_writer, format='PNG', quality=85)
print("\n保存完成")

说明

  • ProgressWriter类会在每次写入数据时计算已写入字节占总大小的比例,输出0.0到1.0之间的进度值。
  • 方式1的总大小是准确值,但需要先将整个图片写入内存,超大图片可能会占用过多内存;方式2是估算值,内存占用低,压缩比可根据实际保存的图片大小调整。
  • 进度输出使用\r实现单行覆盖,避免控制台刷屏。

内容的提问来源于stack exchange,提问作者Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:12:38