python 处理请求获取的图片

环境:python2 (目前使用的环境,虽然比较喜欢使用python3)
图片只有一个图片链接 http://img2.suv.cn/2018/0115/1515977939198935.jpg

1 请求网络图片

import requests
import StringIO
import PIL
from PIL import Image

pic_url = "http://img2.suv.cn/2018/0115/1515977939198935.jpg"
r = requests.get(pic_url)

2 读取图片

f = StringIO.StringIO(r.content)
im = Image.open(f)

3 保存图片

im.save("one.jpg")

该操作可能报错
raise IOError(“decoder %s not available” % decoder_name)
IOError: decoder jpeg not available
原因:PIL的jpg图片支持组件没有安装
解决方法:

1    yum install libjpeg-turbo-devel  libjpeg-turbo-static libjpeg-turbo libjpeg-turbo-utils
2   pip uninstall PIL
3   pip install pillow

4 图片其他处理

裁剪

temp_img = im.crop((0,0,400,400))

调整大小

out_img = temp_img.resize((200,200), resample=PIL.Image.LANCZOS)

更改 resample 的值可改变输出图片的质量。
更多图片操作间 pil 的文档。或者其他可参考文档 http://python.jobbole.com/83685/

以上关于 StringIO 的介绍可参考文档说明,python3 中的引用方式与python2 中有区别。

猜你喜欢

转载自blog.csdn.net/a1368783069/article/details/79093877
今日推荐