Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 739
Steffen Avatar asked Jul 21 '11 11:07

Steffen


People also ask

How do I copy an image to another image in Python?

Call the paste() method from the background image and set the image to paste. By default, the image is pasted at the position where the upper left of the paste image is the origin (upper left) of the base image.

How do I import an image into Python using PIL?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).

What is image Fromarray?

fromarray - Function. 1.1.1 Construct a CASA image from a numerical (integer or float) array. This function converts a numerical (integer or float) numpy array of any size and dimensionality into a CASA image. It will create both float and complex valued images.


1 Answers

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) 
like image 187
Ferdinand Beyer Avatar answered Oct 10 '22 15:10

Ferdinand Beyer