简体   繁体   中英

Python copy on PIL image object

I'm trying to create a set of thumbnails, each one separately downscaled from the original image.

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)

The above code seemed to work fine but while testing I discovered that some images (I can't tell what's special about them, maybe only for PNG) raise this error:

/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' 

Without the copy() these images work just fine.

I could just open and crop the image anew for every thumbnail, but I'd rather have a better solution.

I guess copy.copy() does not work for the PIL Image class. Try using Image.copy() instead, since it is there for a reason:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM