python图片转换成文字_python-如何将.png图像转换为字符串并通过Dj...

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

请告诉我hoe解决此问题,或者是否有更好的方法来解决此问题.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值