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()
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值