Reputation: 37846
imgfile = open('myimage.png', 'wb')
imgfile.write(decodestring(base64_image))
f = Image.open(imgfile)
imgfile.close()
i am being able to write()
base64 string as image into imgfile
. but when I try to open this file with PIL, i am getting
File not open for reading
what am I doing wrong?
Upvotes: 0
Views: 6408
Reputation: 1121186
You opened the file for writing, not reading. You'd have to use a dual mode, and first rewind the file pointer:
with open('myimage.png', 'w+b') as imgfile:
imgfile.write(decodestring(base64_image))
imgfile.seek(0)
f = Image.open(imgfile)
Here w+
means writing and reading, see the open()
documentation:
'+'
open a disk file for updating (reading and writing)For binary read-write access, the mode
'w+b'
opens and truncates the file to 0 bytes.'r+b'
opens the file without truncation.
However, there isn't really any need to use a file on disk here; use an in-memory file instead:
from io import BytesIO
imgfile = BytesIO(decodestring(base64_image))
f = Image.open(imgfile)
Upvotes: 2
Reputation: 1436
The problem here is that you are opening the file for writing with wb
, use w+b
to open for reading as well.
Detailed explanation in the docs here.
Upvotes: 0