[英]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.