PIL - Image.open() problem

Fredrik Lundh fredrik at pythonware.com
Mon Oct 29 06:12:11 EST 2001


Per Jensen wrote:

> Problem: I have a method in a classe which sometimes open a JPEG image,
> and at other times do not.

> ---------------------------------------------
> Opening picture: "1.jpg"
> Traceback (most recent call last):
>   File "./picture.py", line 155, in getImage
>   self.picture = Image.open(self.filename)
>   File "/var/tmp/python-imaging-root//usr/lib/python2.0/site-packages/PIL/Image.py", line 871, in open
>   prefix = fp.read(16)
> AttributeError: read
> --------------------------------------------

could it be that someone's passing you a unicode string?
PIL's file-or-string code doesn't deal properly with unicode
strings:

>>> import Image
>>> i = Image.open("lena.jpg")
>>> i = Image.open(u"lena.jpg")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "c:\py21\PIL\Image.py", line 936, in open
    prefix = fp.read(16)
AttributeError: read
>>>

try changing your code to:

    self.picture = Image.open(str(self.filename))

or, if you're on a platform that can handle unicode filenames:

    self.picture = Image.open(open(self.filename, "rb"))

:::

note that 2.2 is a bit more helpful:

Python 2.2b1 (#25, Oct 19 2001, 21:26:51)
>>> import Image
>>> i = Image.open("lena.jpg")
>>> i = Image.open(u"lena.jpg")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "c:\py22\PIL\Image.py", line 936, in open
    prefix = fp.read(16)
AttributeError: 'unicode' object has no attribute 'read'

</F>





More information about the Python-list mailing list