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(
    print str



Convert String to Image

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

fh = open("imageToSave.png", "wb")
Category >> Python  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. jone on 2014-2-18

    hy buddy help me

  2. jone on 2014-2-18

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

  3. thisweekinstupid on 2015-1-7

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

  4. Zubair on 2015-1-13

    Thank U So much for this Code 🙂

  5. Zubair on 2015-1-13

    By this U can easily send the Image through ZMQ Sockets

Leave a comment