问题
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:
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.
来源:https://stackoverflow.com/questions/41850407/image-from-bytes-python