PIL从内存中加载图片

最近有个需求是从网上得到图片后直接用PIL打开进行修改,看了PIL.Image里没有相应的方法,试了下用open打开文件,再用Image.open打开,没有报错。

>>> f = open('2019.jpg', 'rb')
>>> f
<_io.BufferedReader name='2019.png'>
>>> im = Image.open(f)
>>> im
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=500x500 at 0x1DEC5E32BA8>

从网上查了下,说可以用StringIO或者BytesIO来实现。去找官方文档:

Binary I/O

Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects. No encoding, decoding, or newline translation is performed. This category of streams can be used for all kinds of non-text data, and also when manual control over the handling of text data is desired.
The easiest way to create a binary stream is with open() with ‘b’ in the mode string:
f = open("myfile.jpg", "rb")
In-memory binary streams are also available as BytesIO objects:
f = io.BytesIO(b"some initial binary data: \x00\x01")
The binary stream API is described in detail in the docs of BufferedIOBase.

也就是说,用BytesIO读取数据和用open以二进制模式打开文件都创建了一个二进制流。我们用它来实现:

import requests
from PIL import Image
from io import BytesIO

response = requests.get('图片链接')
if response.status_code == requests.codes.ok:
    img_data = response.content
    
	im = Image.open(BytesIO(img_data))
	im.show()

你可能感兴趣的:(Python)