通过python请求zimg服务,包括图片上传下载

前言

已经部署了zimg服务且在浏览器端测试通过了,部署详情参考zimg官方文档

包加载

import requests,sys,json
from PIL import Image
from io import StringIO,BytesIO
from bs4 import BeautifulSoup

下载:get请求

根据官方案例来看,请求图片数据采用get方式,比较简单:

# 接口访问
url = 'http://[zimp_server_ip]:4869/[image_MD5]?w=300'
result = requests.get(url)
# 图片查看
content = result.content
image = Image.open(BytesIO(content))
image

上传:post请求

根据官方文档来看,上传图片采用post方式,有两种:raw-post 与 form表单。

raw-post方式(返回json)
# 基本信息
url_post = 'http://[zimp_server_ip]:4869/upload' 
img_path = 'xxxx.jpg' 
header = {'content-type': "jpeg"} # 需要头,"jpeg"写其他的格式好像也不影响

# -----------------------下边代码有bug,现在舍弃-----------------------#
# # 打开图片,并生成二进制
# img_info = Image.open(img_path)
# imgByteArr = BytesIO()
# img_info.save(imgByteArr, format='JPEG')
# imgByteArr = imgByteArr.getvalue()
# # 图像提交
# result = requests.post(url=url_post,data=imgByteArr,headers=header)
# -----------------------现在开始为推荐代码----------------------------#

# 打开图片,并生成二进制
img_info = open(img_path,'rb')
# 图像提交
result = requests.post(url=url_post,data=img_info,headers=header)
# 结果接收
if result.status_code == 200:
    result_dict = json.loads(result.content.decode())
    if result_dict['ret']:
        print('上传成功!MD5:%s'%result_dict['info']['md5'])
    else:
        print('上传失败!原因:%s'%result_dict['error']['message'])
form表单方式(返回html)
# 打开图片
img_data = open(img_path,'rb') # 二进制模式,不做任何解码处理
# 表单生成
files = {'blob':(None,img_data),
		 'type':(None,'image/jpeg')}
# 图像提交
result = requests.post(url=url_post,files=files) 
# 结果接受
if result.status_code == 200:
    result_html = result.content.decode()
    # print('%s'%result_html) # 查看html内容
    text = BeautifulSoup(result_html, "lxml").body.text.strip().split('\n') # 用BeautifulSoup解析,获取内容
    # print(text) # 查看文字内容
    print('上传成功!%s'%[i for i in text if 'MD5' in i][0]) 

应该都能看的懂,有疑问留言吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值