python读取浏览器端图片
导入相关python包
python 3.X版本
from io import StringIO
from urllib.request import urlopen
from PIL import Image
python 2.X版本
import urllib2
import cStringIO
from PIL import Image
相关code
file = urlopen(item) #item为相应url
tmpIm = StringIO(file.read())
singleImage = Image.open(tmpIm) # type: ignore
1.如果code为3.6及以下版本:
Image.open()可能会无法读取StringIO类型参数,需加上type:ignore
亲测3.10版本完全正常
2.如果urlopen读取url返回401时,应该时该访问url需要带着验证进行访问,需自己写一个验证相关函数访问。(我太菜了写着太累)
3.同时如果路径为本地的绝对路径或者虚拟路径,可以直接Image.open()
singleImage = Image.open(file_input_path)
读取相关尺寸并修改
width = singleImage.width
height = singleImage.height
resized_image = singleImage.resize((width,height), Image.ANTIALIAS)
Image.save(file_out_path)
如果是本地路径需要替换原图片时,直接file_input_path = file_out_path即可
该博客介绍了如何使用Python的urllib和PIL库从网络读取图片,处理包括401错误的访问问题以及图片尺寸的读取和修改。针对不同Python版本提供了相应的代码示例,并详细说明了本地文件的处理方式。





