5

I have a array of bytes in python (converted from an arbitrary text file) and would like to use those bytes as RGB values to store in an image. What is the best way to do this? thanks

1 Answer 1

4

That's kind of a late response but maybe it helps others in the future: Hopefully I interpreted your question right, but if your "arbitrary text file" represents the structure of an image file like ".jpg" you can just change the files extension from ".txt" to ".jpg" and import it with PIL for example.

You can do something like this:

from PIL import Image

path_to_file = 'path/to/arbitraty_textfile.txt'
safe_path = path_to_file.replace('.txt','.jpg')

with open(path_to_file,'rb') as textfile:
  bytestring = textfile.read()

  with open(safe_path, 'wb') as imagefile:
    imagefile.write(bytestring)


#Import with PIL
image = Image.open(safe_path)

# ...

If you want to read or write a string of bytes in python the attribute 'rb' or 'wb' is the key word here.

Let me know if this is close to the solution, that you've already found I guess.

Sign up to request clarification or add additional context in comments.

1 Comment

This was close enough. The file I used to test this with contained utf-8 characters. I wanted to use the byte values of those characters as RGB values. So let's say the first character is 2 bytes, it would represent the red and green value and the first byte of the next character would be the Blue byte and so on. Interestingly enough this worked well enough for me to use!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.