Strange IOError when opening base64 string in PIL

前端 未结 2 1000
终归单人心
终归单人心 2021-01-14 00:08

I tried encoding an image and decoding the same in python shell. The first time I open the decoded base64 string in PIL there is no error, if I repeat the Image.open() comma

相关标签:
2条回答
  • 2021-01-14 01:01

    When you create your image_string, you're creating a fake file-like object backed by a string. When you call Image.open, it reads this fake file, moving the file pointer to the end of the file. Attempting to use Image.open on it again just gives you an EOF.

    You need to either re-create your StringIO object, or seek() to the beginning of the stream.

    0 讨论(0)
  • 2021-01-14 01:06

    image_string is file-like object. File-like object has file position.

    Once the file is read, the position is advanced.

    Any subsequent is occurred at that position unless you explicitly position it using seek method.

    So if you want to reopen the file:

    ...
    image_string.seek(0) # reset file position to the beginning of the file.
    img = Image.open(image_string)
    
    0 讨论(0)
提交回复
热议问题