Python Implements Images Base64 Encode for Beginners – Python Tutorial

By | November 17, 2019

Images are often encoded to display or transfer in web development, how to encode them? In this tutorial, we will discuss how to encode an image with base64 algorithm for beginners in python.

Preliminary

import base64 model in python

import base64

Open an image with rb model

You must open an image with rb model.

with open(image, 'rb') as fin:

Read image data to implement base64 encode

    data = fin.read()
    base64_data = base64.b64encode(data)

Then python variable base64_data is the result.

However, we will find the type of base64_data is byte. To convert it to string, you can do like this:

    base64_data_str = base64_data.decode("utf-8")
    print(base64_data_str)

From the result string, we will find some special characters like: +, / et al.

python base64encode image

To avoid these special characters, you can read this tutorial.

Improve Python Base64 to Encode String Safely: Replace +, / and = Characters

Meanwhile, after encoding an image, you plan to send it to remote server, how to do? You can read this tutorial.

A Simple Guide to Python 3 Urllib Post Data to Server