'Image' object has no attribute 'read'

江枫思渺然 提交于 2021-02-05 07:40:58

问题


I want to use the images stored in a dictionary, to convert it to a GIF. The images in the dictionary is like this type:

people={
    1: <PIL.Image.Image image mode=RGBA size=16x16 at 0x10962C510>,
    2: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F90>,
    3: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F50>}

I think is a Pillow image. But why do I always get this error:

'Image' object has no attribute 'read'

What does it mean?

The full error:

File "/***view.py", line 266, in convert_gif
    new_frame = Image.open(imgs[count])
File "/***/python3.7/site-packages/PIL/Image.py", line 2775, in open
    prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read' –

The code:

self._images = { 
    people: {
        1: <PIL.Image.Image image mode=RGBA size=16x16 at 0x10962C510>, 
        2: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F90>, 
        3: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F50>
    }
}

def convert_gif(self):

    imgs = self._images["people"]
    number = len(imgs)
    count=1

    while count <= number:
        new_frame = Image.open(imgs[count])
        self._frames.append(new_frame)
        count += 1

    self._frames[0].save('png_to_gif.gif', format='GIF', append_images=self._frames[1:], save_all=True, duration=300, loop=0)

回答1:


As others have pointed out in the comments, the problem is this:

imgs = self._images["people"]
...
new_frame = Image.open(imgs[count])

The error comes from Image.open, which expects you to pass it a file object (the fp param). In Python, file objects have a read method, and Image.open simply calls that read method on the passed file object. It reads the image file and converts it to an Image object.

But if you check the type of imgs[count], it already is an Image object.

curr_img = imgs[count]
print(curr_img)  
# <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=240x160 at 0x7F5C00B74588>

And Image objects don't have a read method, and they shouldn't have one because the image data is already loaded into memory. You can now use Image-related functions on the object, like appending them to a list to create a GIF.

So simply remove the Image.open call and it's going to work as expected.

while count <= number:
    new_frame = imgs[count]
    self._frames.append(new_frame)
    count += 1


来源:https://stackoverflow.com/questions/58468944/image-object-has-no-attribute-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!