Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法解码base64编码的图像_Python_Python 3.x_Python Requests_Base64 - Fatal编程技术网

Python 无法解码base64编码的图像

Python 无法解码base64编码的图像,python,python-3.x,python-requests,base64,Python,Python 3.x,Python Requests,Base64,我是python新手。我的任务是构建一个API端点,该端点获取图像并返回图像。因此,我选择了flask来完成我的工作 我接着问了这个问题——让API端点上传图像文件 代码如下: from flask import Flask, render_template , request , jsonify from PIL import Image import os , io , sys import numpy as np import cv2 import base64 app = Flask

我是python新手。我的任务是构建一个API端点,该端点获取图像并返回图像。因此,我选择了
flask
来完成我的工作

我接着问了这个问题——让API端点上传图像文件

代码如下:

from flask import Flask, render_template , request , jsonify
from PIL import Image
import os , io , sys
import numpy as np 
import cv2
import base64

app = Flask(__name__)

start_point = (0, 0) 
end_point = (110, 110) 
color = (255, 0, 0)
thickness = 2

@app.route('/image' , methods=['POST'])
def mask_image():
    file = request.files['image'].read()
    npimg = np.fromstring(file, np.uint8)
    img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)
    img = Image.fromarray(img.astype("uint8"))
    rawBytes = io.BytesIO()
    img.save(rawBytes, "png")
    rawBytes.seek(0)
    img_base64 = base64.b64encode(rawBytes.read())
    return jsonify({'status':str(img_base64)})


if __name__ == '__main__':
    app.run(debug = True)
然后,我使用向API发送了一个请求

但我无法解码base64响应。我试过的代码

import requests
import base64

files = {'image': open('image.png','rb')}
r = requests.post("http://localhost:5000/image", files=files)
print(base64.decodestring(r.text))
但这是一个错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/anaconda3/envs/py37/lib/python3.7/base64.py in _input_type_check(s)
    509     try:
--> 510         m = memoryview(s)
    511     except TypeError as err:

TypeError: memoryview: a bytes-like object is required, not 'str'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-192-e8ba5f9daae3> in <module>
----> 1 base64.decodestring(r.text)

~/anaconda3/envs/py37/lib/python3.7/base64.py in decodestring(s)
    552                   "use decodebytes()",
    553                   DeprecationWarning, 2)
--> 554     return decodebytes(s)
    555
    556

~/anaconda3/envs/py37/lib/python3.7/base64.py in decodebytes(s)
    543 def decodebytes(s):
    544     """Decode a bytestring of base-64 data into a bytes object."""
--> 545     _input_type_check(s)
    546     return binascii.a2b_base64(s)
    547

~/anaconda3/envs/py37/lib/python3.7/base64.py in _input_type_check(s)
    511     except TypeError as err:
    512         msg = "expected bytes-like object, not %s" % s.__class__.__name__
--> 513         raise TypeError(msg) from err
    514     if m.format not in ('c', 'b', 'B'):
    515         msg = ("expected single byte elements, not %r from %s" %

TypeError: expected bytes-like object, not str
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
~/anaconda3/envs/py37/lib/python3.7/base64.py输入类型检查
509试试:
-->510米=记忆视图(s)
511除类型错误作为错误外:
TypeError:memoryview:需要类似字节的对象,而不是“str”
上述异常是以下异常的直接原因:
TypeError回溯(最近一次调用上次)
在里面
---->1 base64.decodestring(r.text)
解码字符串中的~/anaconda3/envs/py37/lib/python3.7/base64.py
552“使用解码字节()”,
553弃用警告,2)
-->554个返回字节
555
556
~/anaconda3/envs/py37/lib/python3.7/base64.py,以解码字节为单位
543个def解码字节:
544“将base-64数据的bytestring解码为字节对象。”“”
-->545输入类型检查
546返回binascii.a2b_基地64(s)
547
~/anaconda3/envs/py37/lib/python3.7/base64.py输入类型检查
511除类型错误作为错误外:
512 msg=“应该是像对象一样的字节,而不是%s”%s.\u类\u.\u名称__
-->513从err引发类型错误(msg)
514如果m.格式不在('c','b','b'):
515 msg=(“应为单字节元素,而不是%s中的%r”%
TypeError:应为类似对象的字节,而不是str

如何解码图像?

尝试
r.content
它是字节,而不是
r.text
它是字符串。

两件事,首先需要字节,而不是字符串。您需要使用
r.content
r.text.encode('utf8'))
获取字节。另外,
decodestring
也不推荐使用,因此您不应该使用它。通常,除非您有充分的理由不这样做,否则您应该使用来解码base64数据

其次,
/image
端点返回一个包含base64图像的JSON对象。您的客户端必须首先从JSON响应中提取图像数据,然后对其进行解码。
响应
对象包含一个对此有用的
.JSON()
方法:

import requests
import base64

files = {'image': open('image.png','rb')}
r = requests.post("http://localhost:5000/image", files=files)
print(base64.b64decode(r.json()['status']))

标记的答案是我自己的。因此,我将提供答案

其中一个用户@ToxicCode已经给出了99%的答案。但是这里有一个陷阱。脚本以字节字符串的形式发送响应,如下图所示

"b'iVBORw0KGgoAAAANSUhEUgAABXYAAAOOCAIAAAAru93tAAEAAElEQVR4nOz9eZRk+V3ffX5+98a+ZkbutbZ2gZAx6DFgsEGHHRtrsC0xFgezGGg3to8H2+NlQGjmSAI/D4wfGD/40AiZRTDgBwkMGI9AwjoCzGLZgLHYZEmou5bMjFwiMjPWu37nj4iqzOqur
...
..
字节
b
已经存在于字符串中。因此,如果您遵循@ToxicCode,您将面临错误。因此,作为一种糟糕的方法,您可以使用
ast.literal\u eval
转换为字符串,然后遵循@ToxicCode代码

重要提示:不要在生产服务器中使用
ast.literal\u eval()
。相应地更改实现

import ast
import requests
import base64

files = {'image': open('image.png','rb')}
r = requests.post("http://localhost:5000/image", files=files)
data = ast.literval_eval(r.json()['status'])
print(base64.b64decode(data))

我不使用Anaconda,粗略地看一眼之后,现在唯一可以建议的另一件事是执行
print(base64.decodebytes(r.content))
,因为它对我有用&
decodestring
给了我一个“弃用警告:decodestring()是自Python 3.1以来弃用的别名”