2

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?

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Tried it a couple times, but it doesnt work for 3.7. base64.encodestring(s) is deprecated since Python 3.1.
base64.standard_b64encode(content) is another way of doing the same thing. I encoded the image using this method check the code. Please check the link. docs.python.org/3.7/library/…
1

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

1 Comment

second line it has to be image.read()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.