类型错误:预期的类似字节的对象,而不是 str [英] TypeError: expected bytes-like object, not str

查看:32
本文介绍了类型错误:预期的类似字节的对象,而不是 str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know this question has been asked much times, but please look once in my problem.

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

I am sending base64 image data from angular to python flask but when I am processing that base64 data on flask server(python3) then it is giving me the error

TypeError: 预期的类似字节的对象,而不是 str

TypeError: expected bytes-like object, not str

我的Javascript代码是:

My Javascript code is:

window['__CANVAS'].toDataURL("image/png");

上面一行的输出是:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....."

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

I am receiving same data on flask server as string.

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

Code on python server that is using above base 64 data is:

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

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

then it is giving the following error trace:

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

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

above python function working fine if I am converting the image using this function

import base64

with open("t.png", "rb") as imageFile:
  str = base64.b64encode(imageFile.read())
  print str

请帮我解决这个问题?我是 Python 新手.

please help me to solve this question? I am new to python.

推荐答案

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

base64.decodebytes only accepts byte arrays, use base64.b64decode instead it accepts Strings as well

这篇关于类型错误:预期的类似字节的对象,而不是 str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆