python - 将 PILLOW 图像转换为 StringIO

标签 python python-imaging-library python-2.x stringio

我正在编写一个程序,它可以接收各种常见图像格式的图像,但需要以一种一致的格式检查所有图像。什么图像格式并不重要,主要是它们都是相同的。因为我需要转换图像格式然后继续处理图像,所以我不想将它保存到磁盘;只需转换它并继续。这是我使用 StringIO 的尝试:

image = Image.open(cStringIO.StringIO(raw_image)).convert("RGB")
cimage = cStringIO.StringIO() # create a StringIO buffer to receive the converted image
image.save(cimage, format="BMP") # reformat the image into the cimage buffer
cimage = Image.open(cimage)

它返回以下错误:

Traceback (most recent call last):
  File "server.py", line 77, in <module>
    s.listen_forever()
  File "server.py", line 47, in listen_forever
    asdf = self.matcher.get_asdf(data)
  File "/Users/jedestep/dev/hitch-py/hitchhiker/matcher.py", line 26, in get_asdf
    cimage = Image.open(cimage)
  File "/Library/Python/2.7/site-packages/PIL/Image.py", line 2256, in open
    % (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringO object at 0x10261d810>

我也尝试过使用 io.BytesIO 得到相同的结果。关于如何处理这个问题有什么建议吗?

最佳答案

根据实例的创建方式,cStringIO.StringIO() 对象有两种;一个只用于阅读,另一个用于写作。你不能互换这些。

当您创建一个 cStringIO.StringIO() 对象时,您实际上得到了一个cStringIO.StringO(注意O 最后)类,它只能作为输出,即写入。

相反,用初始内容创建一个对象会生成一个 cStringIO.StringI 对象(以 I 结尾用于输入),您永远不能写入它,只能从中读取。

cStringIO 模块是特别的; StringIO(纯 python 模块)没有这个限制。 documentation使用别名 cStringIO.InputTypecStringIO.OutputType对于这些,有话要说:

Another difference from the StringIO module is that calling StringIO() with a string parameter creates a read-only object. Unlike an object created without a string parameter, it does not have write methods. These objects are not generally visible. They turn up in tracebacks as StringI and StringO.

使用 cStringIO.StringO.getvalue() 从输出文件中获取数据:

# replace cStringIO.StringO (output) with cStringIO.StringI (input)
cimage = cStringIO.StringIO(cimage.getvalue())
cimage = Image.open(cimage)

可以使用io.BytesIO()相反,但是你需要在写完后倒带:

image = Image.open(io.BytesIO(raw_image)).convert("RGB")
cimage = io.BytesIO()
image.save(cimage, format="BMP")
cimage.seek(0)  # rewind to the start
cimage = Image.open(cimage)

关于python - 将 PILLOW 图像转换为 StringIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920728/

相关文章:

python - 将 beautifulsoup 输出转换为矩阵

python - AWS Elastic Beanstalk Django - 部署到 EB 时首先发生什么,pip install -r requirements.txt 或配置文件中的命令

python - 旋转后的图片看起来像缺少像素

python - 如何从模块中只加载一个类?

python - 如何确定创建闭包的函数?

python - 属性错误 : 'function' object has no attribute 'func_name' and python 3

python - hasattr 与函数

python - Pandas.to_datetime() 仅在数据框中的列上失败

python - Django : Joining two tables and using extra field from second table for order_by

python - PIL : How to make area transparent in PNG?