Open In App

Python – Convert Image to String and vice-versa

Improve
Improve
Like Article
Like
Save
Share
Report

To store or transfer an Image to some we need to convert it into a string such that the string should portray the image which we give as input. So In Python to do this Operation, it is a straight forward task not complicated because we have a lot of functions in Python available.

Convert Image To String

  • Here First We Import Base64 Method To Encode The Given Image 
  • Next, We Opened Our Image File In rb Mode Which Is Read In Binary Mode.
  • The We Read Our Image With image2.read() Which Reads The Image And Encode it Using b64encode() It Is Method That Is Used To Encode Data Into Base64 
  • Finally, we Print Our Encoded String 

Image used:

Python3




import base64
  
  
with open("food.jpeg", "rb") as image2string:
    converted_string = base64.b64encode(image2string.read())
print(converted_string)
  
with open('encode.bin', "wb") as file:
    file.write(converted_string)


Output:

This Is The Output Of  Image That is Converted To String Using Base64

Here We got the output but if you notice in Starting Of String we get this b’ This We Can Say As Base64 Encoded String in Pair of single quotation. So if we want to remove that we can do the Following By Replacing The Print Statement With print(my_string.decode(‘utf-8’))

Convert String To Image

Here To Convert It From String It Is Actually A Reverse Process Which Is Also Straight Forward Method

  • First We Import Base64. Then We Open Our binary File Where We Dumped Our String. Then Open The File rb Mode Which Is Read In Binary Mode.
  • Store The Data That was Read From File Into A Variable. Then Close The File 
  • Then Just Give Any Image File Name (ex:”myimage.png”) And Open It In wb Mode Write In  Binary 
  • Decode The Binary With b64.decode() Then Close The File With .close()

Note: We will use the above-created string for converting it back to the image

Python3




import base64
  
  
file = open('encode.bin', 'rb')
byte = file.read()
file.close()
  
decodeit = open('hello_level.jpeg', 'wb')
decodeit.write(base64.b64decode((byte)))
decodeit.close()


Output:



Last Updated : 23 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads