将jpeg字符串转换为PIL图像对象

mt8*_*t88 9 python jpeg python-imaging-library

我已经从应用程序的后端传递了一个文件列表,这些文件应该是jpeg文件.然而,对于我的生活,我无法将它们转换为PIL图像对象.我打电话的时候

str(curimg)
Run Code Online (Sandbox Code Playgroud)

我回来了:

<type 'str'>
Run Code Online (Sandbox Code Playgroud)

.我已经尝试过使用open(),. read,io.BytesIO(img.read()并且对它没有任何作用,但它一直把它看作一个字符串.当我打印字符串时,我会得到无法识别的字符.有没有人知道如何告诉python如何将这个字符串作为jpeg解释并将其转换为一个药丸图像,我可以调用.size和np.array?

Die*_*rez 19

同样的事情,但有点简单

from PIL import Image
import io
Image.open(io.BytesIO(image))
Run Code Online (Sandbox Code Playgroud)

注意:

如果图像在网上; 你需要先下载它.

import requests
image = requests.get(image_url).content  #download image from web
Run Code Online (Sandbox Code Playgroud)

然后将其传递给io模块.

io.BytesIO(image)
Run Code Online (Sandbox Code Playgroud)

如果图像在你的高清; 你可以直接用PIL打开.

Image.open('image_file.jpg')  #image in your HD
Run Code Online (Sandbox Code Playgroud)


Ian*_*ohn 12

您应该能够将StringIO对象传递给PIL并以这种方式打开它.

即:

from PIL import Image
import StringIO
tempBuff = StringIO.StringIO()
tempBuff.write(curimg)
tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL
Image.open(tempBuff)
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用 python 3.6,并且收到此错误“StringIO 无法用于打开图像。” ValueError: StringIO 无法用于打开图像。必须使用二进制数据。`如果我使用此方法 (4认同)