简体   繁体   中英

How to get response of an image in django api, after encoded it in base64?

I am trying to make an django api, which accepts image from post method. After that, I change it to grayscale and then, I tried sending back that image as HttprResponse after encoded it into base64. (Actually, I don't know how to send base64 encoded string as reponse. I am new to python). Here's my code:

# 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

I am using postman to test.

邮递员预览

And from HttpResponse I am getting a lot of strings as you can see in above image. I copied those strings and tried to decode it online to get the final image. To which I get no image:

在线base64到图像的对话

So, how to get image(base64 encoded) in response django api.

You have to encode it as jpg (assuming your image is in JPG format) first then you can call final = base64.b64encode(gray) ont it! This is because cv2.cvtColor() will return <class 'numpy.ndarray'> numpy array which can't be encoded as base64 just directly!

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

final contains now a valid base64 string for your image which can be easily returned back!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM