Image from bytes (python)

后端 未结 1 1319
逝去的感伤
逝去的感伤 2021-01-19 20:40

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 th

相关标签:
1条回答
  • 2021-01-19 21:40

    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.

    0 讨论(0)
提交回复
热议问题