Python Web开发——base64 图片

Python Web开发——base64 图片

Base64

Base64是一种编码方式,它是一种基于64个可打印字符来表示二进制数据的表示方法,由于每6个比特为一个单元,对应某个可打印字符。3个字节相当于24个比特,对应于4个Base64单元,即3个字节可由4个可打印字符来表示。Base64常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据,包括MIME的电子邮件及XML的一些复杂数据。

在我这里应用的时候是用于flask参数请求,将本地图片转换为base64进行传输;

这里着重介绍一下图像与base64相互转换,以及在flask中的应用;

图片与base64相互转换

对于图像而言,在计算机存储中,是以一个图像矩阵的形式进行存储,矩阵中的值为[0, 255]之间, 一般将图片作为web service请求的时候,需要将本地文件转化为字符串的形式进行传输,这里使用base64对本地图像进行编码转换

  • 图片对象,将其转换为base64
import base64

def img2base64(image_path):
	with open(image, 'rb') as f:
   		image = f.read()
   		image_base64 = str(base64.b64encode(image), encoding='utf-8')  # image_base64即是对图像进行base64编码后的内容
        return image_base64
  • base64对象,将其转化为本地图片
import base64
               
def string2RGB(sbase64_string):
	base64_string = str(base64_string)
	if "base64," in base64_string:  # support base64 head
		index = base64_string.index("base64,")
		new_base64_string = base64_string[index+7:]
		base64_string = new_base64_string
	imgdata = base64.b64decode(base64_string)
	image = Image.open(io.BytesIO(imgdata))
	return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

Flask 接收请求

这里以post方式获取请求

def request(task):
    # 请求该接口
    response = requests.post('http:xxxx', data=task)
    # 获取响应数据,并解析JSON,转化为python字典
    result = response.json()
    print(response.status_code)
    print(result)
    return res


def image2base64(image_path):
    with open(image_path, 'rb') as f:
        image = f.read()
        image_base64 = str(base64.b64encode(image), encoding='utf-8')
        return image_base64

参考文献

  • https://zh.wikipedia.org/wiki/Base64

  • cnblogs.com/fengff/p/12531474.html

  • https://tool.chinaz.com/tools/imgtobase

  • https://test-study.readthedocs.io/zh_CN/latest/interface/requests.html

你可能感兴趣的:(Web-service,python,base64)