Image from bytes (python)

ぃ、小莉子 提交于 2019-12-10 16:26:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!