3

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') 
6
  • 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. Commented Dec 27, 2020 at 16:20
  • How about converting to base64? en.m.wikipedia.org/wiki/Base64 Commented Dec 27, 2020 at 16:49
  • @wuerfelfreak I have tried with base64 but when I try it to encode back to image I am getting error. Commented Dec 27, 2020 at 18:52
  • @BoarGules I want to convert it to string because I wanna perform some ciphering operation on image. Commented Dec 27, 2020 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. Commented Dec 27, 2020 at 19:10

1 Answer 1

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') 
Sign up to request clarification or add additional context in comments.

1 Comment

This got me half way there, and then this - stackoverflow.com/questions/50211546/… - 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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.