AppDividend
Latest Code Tutorials

How to Convert Image to Base64 String in Python

0

Base64 encoding enables us to convert bytes containing binary or text data to ASCII characters. By encoding the data, we improve the chances of it being processed correctly by various systems. Some systems don’t understand the data in bytes format, so we have to convert the data.

The purpose of the base64.b64encode() method in Python is to convert the binary data into ASCII-safe “text”. But Python strongly disagrees with that. Python is now very strict about this that bytes.encode() method doesn’t even exist, and so ‘xyz’.encode(‘base64’) would raise an AttributeError.

Now, let’s understand the base64 encoding.

What is Base64 Encoding?

Base64 encoding is the type of conversion of bytes into ASCII characters. In maths, the base of a number system indicates how many different characters represent numbers.

The name of base64 encoding comes directly from a mathematical definition of the bases: we have 64 characters that represent the numbers.

The Base64 character set contains the following.

  1. 26 uppercase letters
  2. 26 lowercase letters
  3. 10 numbers
  4. + and / for new lines

When a computer converts Base64 characters to binary, each Base64 character represents the 6 bits of information.

Convert Image to Base64 String in Python

To convert the Image to Base64 String in Python, we have to use the Python base64 module that provides b64encode() method. Python base64.b64encode() function encodes a string using Base64 and returns that string.

Syntax

base64.b64encode(s[, altchars])

Parameters

The function takes s as an input, and it is the required parameter.

The Optional altchars must be a string of at least length 2 (additional characters are ignored), which defines the alternative alphabet for the + and / characters. This enables an application to, for example, generate URL or filesystem safe Base64 strings. The default is None, for which a standard Base64 alphabet is used.

Return Value

The b64encode() function returns the encoded string.

Example of converting Image to base64 in Python

import base64

with open("grayimage.png", "rb") as img_file:
    b64_string = base64.b64encode(img_file.read())
print(b64_string)

In my project folder, I have an image called grayimage.png. Please make sure that your image path is correct.

In this example, at first, we opened our file in ‘rb’ mode. Then we read the image file.

Python with open() function opens a file and then we can perform whatever operations we want. It automatically closes the file when we won’t need it anymore.

Then encoded it with b64encode() method. You must read an image file before you encode it.

I am getting the long string in the output in the terminal, like the following.

xrfaP11Zcs/PROUWCp7bOF7TZsPuAxAvWmY0EkyUZ+IF49r3aOEYbllIVB7mWkgXr88st9aZVx5+5jE+ihdEZZFSaVUmJZhGNmVQzOxX7mrT//r2OHpHoQ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s6rbGrGT/ikQnOhVNnLimbbxVLeFS8tdmjVOE0wcmkOvu5nF3/apPPxXgEapMdnaqiKGbilvzadZFg503N+Pjyf/UNvhu7oXayGXKPg/F/zbZ6b0Oelqt2f/bgOULOh4mSezS55a4pPLYdFCYi0sLtb3nwukE6J20uCqAfvretNh0+xyFpHt6j/+waFfxcDxzR1s4vY1DdGTn/GVld9rr2Udrf6pN4He6cMWQsw2Ow9fwzl6Og/tk7ZxVa/+h/+9z++2j73iJyXQ+ac+nJy7tinATA6yXOP9RTl8rJbTI/p69m3lsjWkqaTAXj49XV3zil73n4Y4pP6vjHdavM7+vk7MiwuGEZRtJa0KTQeu72y2EICg9k83B7KAcGB9CVAZf8iiK9mxee7P3Qao3L+r/p3DYiXJ8t/SqtghnnP0sZQvr+bUtJtDpo9TAJUELKS0Es3aPJ6nxVHuuwzt9pkynpqfqxcs4uncJBN0zcpMLrofEGBRWz2HNXO0J57woQfpXc1GHd1vTN4T2c8JtwBhjJC7pB7tn2MJ0/lpf+QWuCzMoUGMupPsAIj1x7y+ViO2aFxlP3qH+LLZJcv++B0kzYwmag38ljr9vudS2ZuKec3utBQ4E/PZLSRViNSnP3CSep/KhS1HWWKerK3xvL/Hzydrveh+QnLAAAAAElFTkSuQmCC'

Your string has been printed. But in the starting position of your base64 string, there is a b’.

Or you can say your base64 encoded string is in the pair of single quotation.

To remove b’ from the prefix of base64 code in Python, you can use string.encode(‘utf-8’) method.

import base64

with open("grayimage.png", "rb") as img_file:
    b64_string = base64.b64encode(img_file.read())
print(b64_string.decode('utf-8'))

That is it for how to convert Image to base64 string in Python example.

See also

Convert PIL Image to Grayscale

Convert PIL Image to Numpy Array

How to crop an image in Python

How to resize an image in Python

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.