原创

【flask request】处理客户端通过POST方法传送的二进制图片数据

做图片识别和检测算法的时候,服务想做成http接口的方式,自然图片传输是一个问题。通常我们是传输二进制文件,那么二进制文件怎么传输呢,下面是我总结的。

1、客服端以post方式传输,files 方式,注意files不是form_data, 是文件。


import os
import requests
import time

def send_post_image_nsfw(img1_path):
    """
    :param img1:
    :return:
    """
    files={
        'img1_path':open(img1_path, 'rb').read()
    }
    html=requests.post('http://127.0.0.1:5200/api/bigdata/v1/image/spam/nsfw',files=files).text
    return html

img1='E:/nsfw_tensorflow/corpus/weibocore_WBC_IMAGE_DATA_SOURCE_6521.jpg'

time1=time.time()
kk=send_post_image_nsfw(img1)
time2=time.time()
print('总共耗时:' + str(time2 - time1) + 's')
print(kk)



2、服务端以 img1_path=request.files[‘img1_path’].stream.read() 方式获取二进制


@app.route("/api/bigdata/v1/image/spam/nsfw", methods=['POST'])
def two_image_similarity():
    if request.method == "POST":
        try:
            img1_path=request.files['img1_path'].stream.read()
            kk =str(nsfw_image_from_yahoo(img1_path))

            result = dict()
            result['code'] = 200
            result['msg'] = "ok"
            result['action'] = 1
            result['similarity'] = kk
            result['gmt_created'] =print_now()
            info(json.dumps(result, ensure_ascii=False))
            return json.dumps(result, ensure_ascii=False)
        except Exception as e:
            debug(e)
            debug('图片post请求出现异常')
            result = dict()
            result['code'] = 200
            result['msg'] = "ok"
            result['action'] = 0
            result['similarity'] = '0'
            result['gmt_created'] = print_now()
            info(json.dumps(result, ensure_ascii=False))
            return json.dumps(result, ensure_ascii=False)

3、那么如何把bytes数组还原成图片呢?

#导入库
from PIL import Image
from io import BytesIO
image = Image.open(BytesIO(file))

4、二进制图片写入内存打开

blob = r[2].read()
f = BytesIO()
f.write(blob)
f_image = Image.open(f)

5、图片二进制base64编码解码

# -*- encoding=utf-8 -*-


import os
import requests
import time

import base64
img1='E:/nsfw_tensorflow/corpus/weibocore_WBC_IMAGE_DATA_SOURCE_6521.jpg'

pimg=open(img1, 'rb').read()

print(pimg)

# base64图片加密
result = base64.b64encode(pimg)

print(result)

# 再把加密后的结果解码
temp = base64.b64decode(result)

print(temp)
正文到此结束
本文目录