从RAM读取.jpg

时间:2019-05-08 18:04:18

标签: python-3.x python-imaging-library

from io import StringIO
from PIL import Image
import requests

response = requests.get(image.url)

# Works fine, but requests a disk write.
f = open('tmp.jpg', 'bw')
f.write(response.content)
img = Image.open('tmp.jpg')

# Fails with `OSError: cannot identify image file <_io.StringIO object at 0x7fb666238a68>`
#file = StringIO(str(response.content))
#img = Image.open(file)

我正在尝试从this tutorial运行代码,但使用的是python3。注释掉的版本是我最原始的想法,即“将图像从网络获取到RAM并使用它”。如果方便,我不介意使用cv2。如何通过Python高效地编写此代码?

1 个答案:

答案 0 :(得分:1)

正如Mark Setchell所说,您可能希望BytesIO而不是StringIO

from io import BytesIO
from PIL import Image
import requests

response = requests.get(image.url)

file = BytesIO(response.content)
img = Image.open(file)