Python: Convert Image to String, Convert String to Image

To store or transfer an image, we often need to convert an image to a string in such a way that the string represents the image. Like other programming languages (e.g. Java), we can also convert an image to a string representation in Python.

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

Output:

iVBORw0KGgoAAAANSUhEUgAAAuAAAACFCAIAAACVGtqeAAAAA3
NCSVQICAjb4U/gAAAAGXRFWHRTb2Z0d2FyZQBnbm9tZS1zY3Jl
ZW5zaG907wO/PgAAIABJREFUeJzsnXc81d8fx9+fe695rYwIaa
...

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()
Category >> Python  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Nishant Joshi

    i tried this to try one of the data compression algorithms, there you compress the string data and decompress and convert it back to bytes and then to image

  • Nishant Joshi

    You saved my life! I was trying huffmans algorithm and got stuck at this last step. Thankyou !!

  • abhijeet singh

    Error:-AttributeError: type object ‘str’ has no attribute ‘decode’

  • Joel Geibel

    i need help: ‘base64’ is not a text encoding; use codecs.decode() to handle arbitrary codecs

  • Ankit Pal

    How we can make an image from datastream coming from server in python?

  • Kamal Jnawali

    why do we need to convert data to string format. I am wondering people are always doing this

  • Vace Dook

    thank you!

  • Zubair

    By this U can easily send the Image through ZMQ Sockets

  • Zubair

    Thank U So much for this Code 🙂

  • You want an optical character recognition package. Google has one called tesseract with a free version available. It interfaces nicely with Python.

    https://code.google.com/p/python-tesseract/

  • jone

    i want to read image and get the text in image as a result….. i dont know how…can anybody help me..

  • jone

    hy buddy help me