解决Pillow报错 Image size (XXX pixels) exceeds limit of 178956970 pixels, could be decompression

解决Pillow报错 Image size (XXX pixels) exceeds limit of 178956970 pixels, could be decompression

1 报错代码

PIL.Image.DecompressionBombError: Image size (244186200 pixels) exceeds limit of 178956970 pixels, could be decompression bomb DOS attack.

在这里插入图片描述

2 报错原因

  原因即图片过大,超过178956970 pixels

3 解决方法

  最初查到的解决方法是在导入ImageFile时添加以下代码

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

运行后还是报错。

最终解决方法为

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
  • 38
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
这个错误提示是因为您尝试保存的图像尺寸太大,超出了 Python Imaging Library (PIL) 的处理能力。PIL 是一个 Python 图像处理库,Matplotlib 使用它来生成图像文件。 为了解决这个问题,您可以尝试以下几种方法: 1. 缩小图像尺寸:您可以使用 Matplotlib 的 `figure()` 函数或 `subplots()` 函数设置图像尺寸。您可以尝试缩小图像尺寸,以使其符合 PIL 的处理能力。例如,将 `figsize` 参数从默认的 `(6.4, 4.8)` 缩小到 `(3.2, 2.4)`。 ```python import matplotlib.pyplot as plt # 绘制图形 plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.title('Sample Plot') # 设置图形尺寸并保存图像 fig = plt.gcf() fig.set_size_inches(3.2, 2.4) plt.savefig('small_plot.png') ``` 2. 使用其他图像处理库:如果您需要保存大尺寸的图像,可以尝试使用其他图像处理库,例如 OpenCV 或 Pillow。这些库可以处理更大的图像尺寸。 ```python import cv2 import matplotlib.pyplot as plt # 绘制图形 plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.title('Sample Plot') # 获取图形数据并保存图像 fig = plt.gcf() fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) cv2.imwrite('large_plot.png', data) ``` 在上面的代码中,我们使用了 OpenCV 库的 `imwrite()` 函数来保存图像。我们首先使用 Matplotlib 的 `canvas.draw()` 方法将图形渲染到画布上,然后使用 NumPy 的 `fromstring()` 函数将数据转换为 NumPy 数组。最后,我们使用 OpenCV 的 `imwrite()` 函数保存图像。 希望这些方法可以帮助您解决问题!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值