Tom
Tom

Reputation: 753

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:

Thanks for your Answers!

Upvotes: 14

Views: 25664

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

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.

Upvotes: 15

Related Questions