Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to turn an IMAGE into a STRING and back?

I have an image like this loaded into a PIL.Image:

enter image description here

And now I want to turn it into a python string, and it should not be binary, how do I do this? Because when I tried to encode I get the following error:

My Code:

from PIL import Image

img = Image.open("testImage.jpeg")
string = img.tobytes()
string = string.decode("ascii")

Output:

Traceback (most recent call last):
  File "/Users/tomschimansky/Desktop/SenderMAIN.py", line 5, in <module>
    string = string.decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

When this works I also want to turn the string back into an image.

Other methods that also don't worked for me:

  • Read the image directly from file with open("file","rb") and then encode it.
  • encode it with the codecs library. (string = codecs.encode(string, "base64"))
  • encode it with the base64 library (was able to convert it to string but the string looked like this: ///////. (only slashes))

Thanks for your Answers!

like image 562
Tom Avatar asked Jan 11 '19 13:01

Tom


People also ask

Can we convert image to string?

String img=o. toString(); byte[] imageAsBytes = Base64. decode(img. getBytes(), Base64.

How do you convert an object to a string in Python?

Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.

How do I convert an image to Base64 in Python?

Convert an image to base64 string in PythonOpen an image file. read the image data. encode it in base64 using the base64 module in Python. Print the string.


1 Answers

You can convert to a string like this:

import base64

with open("image.png", "rb") as image:
    b64string = base64.b64encode(image.read())

That should give you the same results as if you run this in Terminal:

base64 < image.png

And you can convert that string back to a PIL Image like this:

from PIL import Image
import io

f = io.BytesIO(base64.b64decode(b64string))
pilimage = Image.open(f)

That should be equivalent to the following in Terminal:

base64 -D < "STRING" > recoveredimage.png

Note that if you are sending this over LoRa, you are better off sending the PNG-encoded version of the file like I am here as it is compressed and will take less time. You could, alternatively, send the expanded out in-memory version of the file but that would be nearly 50% larger. The PNG file is 13kB. The expanded out in-memory version will be 100*60*3, or 18kB.

like image 135
Mark Setchell Avatar answered Oct 10 '22 08:10

Mark Setchell