Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: expected bytes-like object, not str

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

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: expected bytes-like object, not str

My Javascript code is:

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

Output of the above line is:

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

I am receiving same data on flask server as string.

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

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

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

like image 237
Shubham Batra Avatar asked Nov 16 '18 15:11

Shubham Batra


People also ask

How do you fix a bytes-like an object is required not str?

To solve the Python "TypeError: a bytes-like object is required, not 'str'", encode the str to bytes, e.g. my_str. encode('utf-8') . The str. encode method returns an encoded version of the string as a bytes object.

What is bytes-like object in Python?

Bytes-like object in python In Python, a string object is a series of characters that make a string. In the same manner, a byte object is a sequence of bits/bytes that represent data. Strings are human-readable while bytes are computer-readable. Data is converted into byte form before it is stored on a computer.

Can not use a string pattern on bytes-like object?

The Python "TypeError: cannot use a string pattern on a bytes-like object" occurs when we try to use a string pattern to match a bytes object. To solve the error, use the decode() method to decode the bytes object, e.g. my_bytes. decode('utf-8') .


1 Answers

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

like image 155
wiomoc Avatar answered Oct 23 '22 01:10

wiomoc