【问题标题】:How to convert a .png image to string and send it through Django API?如何将 .png 图像转换为字符串并通过 Django API 发送?
【发布时间】:2018-09-21 13:28:41
【问题描述】:

我正在尝试将 .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

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

【问题讨论】:

  • 该字符串的格式是什么?图片字节流的base64流?
  • 我只想将图像转换为字符串,将其作为响应发送,然后将其转换回 angular page 中的图像。最好的方法是什么?

标签: python django django-rest-framework


【解决方案1】:

您应该使用.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 演示的那样。

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

【讨论】:

    猜你喜欢
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2020-03-22
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多