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. In Python we have a lot of functions in Python available to convert an image into a string.
Image used:

Convert Image To String
To convert an image to a string in Python, we can turn the image into a special text format called base64. This allows us to store or send the image as text which is easier to handle in some situations. We can easily convert it back to an image later.
import base64
# Encode the image to a base64 string.
with open("food.webp", "rb") as img:
s = base64.b64encode(img.read())
print(s)
# Save the encoded string to a file.
with open('encode.bin', "wb") as f:
f.write(s)
Output:
Explanation:
- We import the base64 module to use its b64encode() method for encoding data.
- Image is opened in binary read mode (rb) to read its raw content.
- Image is read using image2string.read() and then encoded into a base64 string with base64.b64encode().
- Finally, the base64-encoded string is printed to view the image in text form.
Note: Here we got the output, but if we notice at the start of the string, we get a
b'. This indicates a base64 encoded string in a pair of single quotations. To remove that, we can replace the print statement withprint(my_string.decode('utf-8')).
Convert String To Image
To convert a base64-encoded string back into an image, we decode the string to retrieve the original binary data. Then, we write the binary data into a new image file. This process allows us to restore the image from its base64 representation.
Example:
import base64 # For decoding.
f = open('encode.bin', 'rb') # Open encoded file.
byte = f.read() # Read data.
f.close()
decode = open('stringtoimage.webp', 'wb') # Open image file to save.
decode.write(base64.b64decode(byte)) # Decode and write data.
decode.close()
Output:

Explanation:
- First, we import the base64 module.
- Open the binary file containing the base64 string in read-binary mode (rb) read the data into a variable and close the file.
- Open a new image file (e.g., "myimage.png") in write-binary mode (wb) and decode the base64 string using base64.b64decode().
- Write the decoded binary data into the file and close it with .close().