PIL图像obj上的Python副本

2024-06-07 17:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一组缩略图,每个缩略图都与原始图像分开缩小比例。

image = Image.open(path)
image = image.crop((left, upper, right, lower))
for size in sizes:
  temp = copy.copy(image)
  temp.thumbnail((size, height), Image.ANTIALIAS)
  temp.save('%s%s%s.%s' % (path, name, size, format), quality=95)

上面的代码似乎工作得很好,但是在测试时,我发现一些图像(我不知道它们有什么特别之处,可能只针对PNG)会引发以下错误:

/usr/local/lib/python2.6/site-packages/PIL/PngImagePlugin.py in read(self=<PIL.PngImagePlugin.PngStream instance>)
line: s = self.fp.read(8)
<type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'read' 

没有copy()这些图像工作得很好。

我可以为每个缩略图重新打开和裁剪图像,但我宁愿有更好的解决方案。


Tags: pathin图像imageselfreadsizepil
1条回答
网友
1楼 · 发布于 2024-06-07 17:38:26

我猜copy.copy()不适用于PIL Image类。尝试使用Image.copy()代替,因为它存在是有原因的:

image = Image.open(path)
image = image.crop((left, upper, right, lower))
for size in sizes:
  temp = image.copy()  # <-- Instead of copy.copy(image)
  temp.thumbnail((size, height), Image.ANTIALIAS)
  temp.save('%s%s%s.%s' % (path, name, size, format), quality=95)

相关问题 更多 >

    热门问题