[英]How to get response of an image in django api, after encoded it in base64?
我正在尝试制作django api,该API接受来自post方法的图像。 之后,将其更改为灰度,然后在将其编码为base64之后,尝试将该图像作为HttprResponse发送回去。 (实际上,我不知道如何发送base64编码的字符串作为响应。我是python的新手)。 这是我的代码:
# import the necessary packages
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpResponse
import numpy as np
import urllib.request
import json
import cv2
import os
import base64
@csrf_exempt
def combine(request):
# check to see if this is a post request
if request.method == "POST":
# check to see if an image was uploaded
if request.FILES.get("image1", None) is not None:
# grab the uploaded image
image1 = _grab_image1(stream=request.FILES["image1"])
# image2 = _grab_image2(stream=request.FILES["image2"])
gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
final = base64.b64encode(gray)
# return a response
return HttpResponse(final)
def _grab_image1(stream=None):
if stream is not None:
data = stream.read()
image1 = np.asarray(bytearray(data), dtype="uint8")
image1 = cv2.imdecode(image1, cv2.IMREAD_COLOR)
# return the image1
return image1
我正在使用邮递员进行测试。
如上图所示,从HttpResponse获得了很多字符串。 我复制了这些字符串,并尝试在线对其进行解码以获得最终图像。 我没有得到的图像:
因此,如何在响应django api中获取图像(base64编码)。
首先,您必须将其编码为jpg(假设您的图像为JPG格式),然后才能调用final = base64.b64encode(gray)
! 这是因为cv2.cvtColor()
将返回<class 'numpy.ndarray'>
numpy数组,该数组不能直接编码为base64!
retval, buffer_img= cv2.imencode('.jpg', gray)
final = base64.b64encode(buffer_img)
final
现在包含用于图像的有效base64字符串,可以轻松返回该字符串!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.