2

Converting in Python is pretty straightforward, and the key part is using the "base64" module which provides standard data encoding an decoding. Convert Image to String

Here is the code for converting an image to a string.

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

Convert String to Image

The following code segment will create an image by using the given string.

fh = open("imageToSave.png", "wb")
fh.write(str.decode('base64'))
fh.close()

But here is t.png enter image description here

And here is imageToSave.png enter image description here

Please brief me if had done sometime wrong till now . here is the error trace

'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs

Thanks for your time.

Hassan ALi
  • 1,313
  • 1
  • 23
  • 51

1 Answers1

2

You should use the same function family to encode and decode the imagedata into/from string.

with open("t.png", "rb") as imageFile:
    imagestr = base64.b64encode(imageFile.read())

with open("imageToSave.png", "wb") as imgFile:
    imgFile.write(base64.b64decode(imagestr))
Flo
  • 2,699
  • 4
  • 24
  • 46