如何将.png图像转换为字符串并通过Django API发送?

时间:2018-09-21 13:28:42

标签: python django django-rest-framework

我正在尝试将.png图像转换为字符串并通过django api发送,但会导致错误

from django.shortcuts import render
from django.http import HttpResponse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import base64

# Create your views here.
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt

def get_res(request):
    if request.method == 'POST':
        x = json.loads(request.body)
        arrx = x['x']
        arry = x['y']
        plt.plot(arrx,arry)
        plt.savefig('plot.png')
        with open('plot.png', 'rb') as imageFile:
            str = base64.b64encode(imageFile.read())
        response = json.dumps([{'image': str}])
        return HttpResponse(response, content_type = 'text/json')

这会导致错误

Internal Server Error: /
Traceback (most recent call last):
  File "C:\lol\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
  File "C:\lol\myenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
  File "C:\lol\myenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\lol\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
  File "C:\lol\apiex\api1\views.py", line 23, in get_res
response = json.dumps([{'image': str}])
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
  File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

请告诉我解决这个问题,或者是否有更好的方法来解决这个问题。

1 个答案:

答案 0 :(得分:3)

您应使用.decode()将二进制字符串转换为字符串:

@csrf_exempt
def get_res(request):
    if request.method == 'POST':
        x = json.loads(request.body)
        arrx = x['x']
        arry = x['y']
        plt.plot(arrx,arry)
        plt.savefig('plot.png')
        with open('plot.png', 'rb') as imageFile:
            data = base64.b64encode(imageFile.read()).decode()
        response = json.dumps([{'image': data}])
        return HttpResponse(response, content_type = 'text/json')

这是一个base64字符串,因此您将必须将该字符串“解码”为客户端上的图像,如演示的here

  

注意:不要不要用类名来命名变量,因为它将“隐藏”对类的引用。