Reputation: 91
I have some images, that I need to give to a server using JSON. I decided to use Base64 as encoding system. In Python 2, I could simply use:
with open(path, "rb") as imageFile:
img_file = imageFile.read()
img_string = base64.b64encode(img_file)
but in Python 3 it doesnt work anymore. What do I have to change to get this in Python 3 to work?
Upvotes: 2
Views: 5006
Reputation: 91
Finally I found a code running on Python 3.7:
# Get the image
image = open(path, 'rb')
image_read = image_read()
# Get the Byte-Version of the image
image_64_encode = base64.b64encode(image_read)
# Convert it to a readable utf-8 code (a String)
image_encoded = image_64_encode.decode('utf-8')
return image_encoded
Upvotes: 1
Reputation: 158
I followed the solution from this link it seems to work for me. So when you read the image in binary convert it to a string and then just encode the string with base64. The following solution is from the link above. Here is the tested code.
import base64
image = open(image, 'rb')
image_read = image.read()
image_64_encode = base64.encodestring(image_read)
Upvotes: 2