2

I am currently doing this for bytestring conversion but I need to convert to string.

img=Image.fromarray(img)
output = io.BytesIO()
img.save(output, format="png")
image_as_string = output.getvalue()
img=Image.open(io.BytesIO(image_as_string))
img.save('strimg.png')
Evil Angel
  • 86
  • 5
  • *Why* do you need to convert it to a string? Strings are for characters, not for images. Strings in Python are not arbitrary bunches of bytes and there are bound to be byte subsequences in your image data that are meaningless when treated as Unicode codepoints. So if you try to convert to a string you will probably get encoding errors. Bytestrings are there to let you do what you are doing without having to worry about what the bytes might mean when interpreted as characters. – BoarGules Dec 27 '20 at 16:20
  • How about converting to base64? https://en.m.wikipedia.org/wiki/Base64 – wuerfelfreak Dec 27 '20 at 16:49
  • @wuerfelfreak I have tried with base64 but when I try it to encode back to image I am getting error. – Evil Angel Dec 27 '20 at 18:52
  • @BoarGules I want to convert it to string because I wanna perform some ciphering operation on image. – Evil Angel Dec 27 '20 at 18:53
  • You can encipher a bytestring. In fact, most encryption library functions *expect* bytestrings, because insisting on Python strings would prevent users like you from doing what you want to do. – BoarGules Dec 27 '20 at 19:10
  • @BoarGules Thanks for your time. May be I will try that. – Evil Angel Dec 27 '20 at 19:42

1 Answers1

3

Here is my solution with base64.

import base64

img = Image.open("test.png")
output = io.BytesIO()
img.save(output, format="png")
image_as_string = base64.b64encode(output.getvalue())

#encrypting/decrypting

img=Image.open(io.BytesIO(base64.b64decode(image_as_string)))
img.save('string.png') 
wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29
  • This got me half way there, and then this - https://stackoverflow.com/questions/50211546/converting-byte-to-string-and-back-properly-in-python3 - got me the rest of the way there. After creating image_as_string, I needed to run img_hex_str = image_as_string.hex(), and then in your 2nd to last line, I had to replace image_as_string with bytes.fromhex(img_hex_str) – yeamusic21 May 11 '23 at 18:32