我在 python 中有一个字节数组(从任意文本文件转换而来),并且想使用这些字节作为 RGB 值来存储在图像中。做这个的最好方式是什么?谢谢
这是一种迟到的回应,但也许它会在将来帮助其他人:希望我正确地解释了你的问题,但是如果你的“任意文本文件”代表像“.jpg”这样的图像文件的结构,你只需更改文件扩展名即可例如,将“.txt”转换为“.jpg”并使用 PIL 导入。
你可以这样做:
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)
# ...
Run Code Online (Sandbox Code Playgroud)
如果你想在 python 中读取或写入字节字符串,属性“rb”或“wb”是这里的关键字。
让我知道这是否接近解决方案,我猜您已经找到了。