1. 需求:需要使用大小不同的图片以供显示
2. 条件:请求服务器图片,在不需要保存其余尺寸图片的情况下,返回任意大小图片
3. 代码:
def handler_size(once, now):
once_x, once_y = once
ratio = once_x / once_y
now_x, now_y = now
if all([now_x, now_y]):
return now
if now_y and not now_x:
return int(ratio * now_y), now_y
if now_x and not now_y:
return now_x, int((1 / ratio) * now_x)
return once
def img(request, path) -> HttpResponse:
"""
:param request: 请求
:param path: 路径
:return: 图片二进制
"""
url = 'http://192.168.0.157:8001/' + mykeys.relieve(path)[:-4]
response = requests.get(url)
if response.status_code == 200:
image_data = response.content
x = int(request.GET.get('x', 0))
y = int(request.GET.get('y', 0))
i = Image.open(BytesIO(image_data))
temp = handler_size(i.size, (x, y))
if temp == i.size:
return HttpResponse(image_data, content_type="image/png")
# 获取原图片的size
out = i.resize(temp, Image.ANTIALIAS)
# 开辟一个内存
f = BytesIO()
# 将图片对象保存到内存中
out.save(f, 'jpeg')
# 取出内存数据,此时就是转化过后的二进制,可直接返回给前端图片流
data = f.getvalue()
else:
data = b''
return HttpResponse(data, content_type="image/png")
网友评论