来自字节的图像(python) [英] Image from bytes (python)

查看:118
本文介绍了来自字节的图像(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个字节数组(从任意文本文件转换而来),并希望将这些字节用作RGB值存储在图像中。做这个的最好方式是什么?谢谢

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

推荐答案

这是一种迟到的反应,但未来可能有助于其他人:希望我能正确解释你的问题,但如果您的任意文本文件表示像.jpg这样的图像文件的结构,您只需将文件扩展名从.txt更改为.jpg,然后使用PIL导入它。

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.

你可以这样做:

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)

# ...

如果你想在python中读取或写入一串字节,属性'rb'或'wb'就是关键字wo rd here。

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.

这篇关于来自字节的图像(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆