Python 在用base64编码后,如何在django api中获得图像的响应?

Python 在用base64编码后,如何在django api中获得图像的响应?,python,django,api,opencv,base64,Python,Django,Api,Opencv,Base64,我正在尝试制作一个DjangoAPI,它接受来自post方法的图像。在那之后,我将其更改为灰度,然后,在将其编码为base64后,我尝试将该图像作为HttpResponse发送回。实际上,我不知道如何发送base64编码字符串作为响应。我是python新手。这是我的密码: # import the necessary packages from django.views.decorators.csrf import csrf_exempt from django.http import Json

我正在尝试制作一个DjangoAPI,它接受来自post方法的图像。在那之后,我将其更改为灰度,然后,在将其编码为base64后,我尝试将该图像作为HttpResponse发送回。实际上,我不知道如何发送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中编码imagebase64

如果您的图像是jpg格式的,您必须将其编码为jpg,然后您可以调用final=base64.b64encodegray!这是因为cv2.CVTColor将返回无法直接编码为base64的numpy数组

retval, buffer_img= cv2.imencode('.jpg', gray)
final = base64.b64encode(buffer_img)

final现在包含图像的有效base64字符串,可以轻松返回

既然您对收到的图像进行了imdecode,那么在发送之前进行imencode难道没有意义吗?您可能不想返回原始像素数据,而是希望以客户端可以理解的格式发送图像…实际上,为什么要将其返回为base64?我正在尝试在android设备中使用它。我在网上读到,上传和获取图像响应的最佳方式是将其转换为base64。