encode base64 python code example

Example 1: python convert image to base64

import base64

file = 'deer.jpg'
image = open(file, 'rb')
image_read = image.read()
image_64_encode = base64.encodebytes(image_read) #encodestring also works aswell as decodestring

print('This is the image in base64: ' + str(image_64_encode))

image_64_decode = base64.decodebytes(image_64_encode) 
image_result = open('deer_decode.jpg', 'wb') # create a writable image and write the decoding result
image_result.write(image_64_decode)

Example 2: base64 encode python

import base64

message = "Python is fun"
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')

print(base64_message)

Example 3: decode base64 python

import base64
msg = base64.b64decode(msg)

Example 4: base64 decode python

>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'

Example 5: base64 python decode

import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)