类型错误:预期的类似字节的对象,而不是 str

Shu*_*tra 9 javascript python base64 angular6

我知道这个问题已经被问过很多次了,但请看一下我的问题。

我正在将base64图像数据从 angular发送到python 烧瓶,但是当我base64在烧瓶服务器(python3)上处理该数据时,它给了我错误

类型错误:预期的类似字节的对象,而不是 str

我的 Javascript 代码是:

window['__CANVAS'].toDataURL("image/png");
Run Code Online (Sandbox Code Playgroud)

上面一行的输出是:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....."
Run Code Online (Sandbox Code Playgroud)

我在烧瓶服务器上收到与字符串相同的数据。

使用以上 base 64 数据的 python 服务器上的代码是:

def convert_to_image(base64_code):
  image_64_decode = base64.decodebytes(base64_code)
  image_result = open('baseimage.jpg', 'wb')
  image_result.write(image_64_decode)
  img_rgb = cv2.imread('baseimage.jpg')
  return img_rgb
Run Code Online (Sandbox Code Playgroud)

然后它给出以下错误跟踪:

File "/home/shubham/py-projects/DX/Web/app/base64toimage.py", line 10, in convert_to_image    
  image_64_decode = base64.decodebytes(base64_code)
File "/usr/lib/python3.5/base64.py", line 552, in decodebytes    
  _input_type_check(s)
File "/usr/lib/python3.5/base64.py", line 521, in _input_type_check  
  raise TypeError(msg) from err 
TypeError: expected bytes-like object, not str
Run Code Online (Sandbox Code Playgroud)

如果我使用这个函数转换图像,上面的 python 函数工作正常

import base64

with open("t.png", "rb") as imageFile:
  str = base64.b64encode(imageFile.read())
  print str
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题?我是python的新手。

wio*_*moc 20

base64.decodebytes只接受字节数组,使用base64.b64decode它也接受字符串