- How to use Python 3 to convert your images to Base64 encoding
- Python 3 codes to encode an image in Base64
- How to display a Base64 encoded image on the browser
- About Clivant
- Python jpeg to base64
- # Table of Contents
- # Convert an Image to a Base64-encoded String in Python
- How to Convert Image to Base64 String in Python
- Syntax
- Parameters
- Return Value
- Example 1: How to convert an Image to base64 in Python
How to use Python 3 to convert your images to Base64 encoding
When you encode your images in Base64, your images can be transferred and saved as text.
Although there will be a 37% bloat in space requirements, it can be useful to encode images in Base64.
For example with SAP HANA XS Advanced, you can quickly build an OData service to receive images via JSON.
Given that, let’s see how we can encode an image in Base64 encoding with Python 3.
Python 3 codes to encode an image in Base64
After you had decided to encode your image in Base64, you can proceed with coding a utility function with Python 3:
import base64 def get_base64_encoded_image(image_path): with open(image_path, "rb") as img_file: return base64.b64encode(img_file.read()).decode('utf-8')
As shown above, it takes just 4 lines of Python 3 codes to encode an image in Base64.
First, we import the base64 module into our Python script.
Once we have done so, we define a function, get_base64_encoded_image , that takes an image path as the parameter.
When we have the image path, we use the open function to get a file object to the image that we wish to encode in Base64.
If we can do so successfully, then we use base64.b64encode on the binary data of the image file.
Before exiting the function, we decode the bytes from base64.b64encode as a UTF-8 string and return it to the caller.
How to display a Base64 encoded image on the browser
Given that you have saved the Base64 encoded image into your database, how can you display it on the browser?
In order to display a Base64 encoded image on the browser, place the Base64 encoded string in the src attribute of an img tag:
When you access the above HTML codes with your browser, you will get the following image:
If you wish to display a different type of image, swap the MIME type.
For example, if you wish to display a png image, you will change:
About Clivant
Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.
Python jpeg to base64
Last updated: Jun 23, 2023
Reading time · 4 min
# Table of Contents
# Convert an Image to a Base64-encoded String in Python
To convert an image to a base64 string in Python:
- Use the with open() statement to open the image file.
- Use the file.read() method to read the image’s contents.
- Use the base64.b64encode() method to encode the bytes using Base64 and return a bytes-like object.
Copied!import base64 with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) print(base64_bytes) base64_string = base64_bytes.decode() print(base64_string)
The code sample assumes that you have the following house.webp image in the same directory as your Python script.
You can right-click on the image and select «Save image as» to download it.
We first imported the base64 native Python module.
The module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data.
The next step is to use the with open() statement to open the image file in rb (read binary) mode.
The with open() statement takes care of closing the file even if an error occurs.
Copied!import base64 with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) print(base64_bytes) base64_string = base64_bytes.decode() print(base64_string)
The base64.b64encode method encodes the supplied bytes-like object using Base64 and returns the encoded bytes.
If you want to convert the base64 encoded bytes to a string, use the bytes.decode method.
Copied!base64_string = base64_bytes.decode() print(base64_string)
The bytes.decode() method converts the bytes object to a string and removes the b prefix.
You can also pass the encoding as an argument to the decode() method.
The default encoding is utf-8 .
Copied!base64_string = base64_bytes.decode('utf-8') print(base64_string)
The first argument we passed to the open() function is the path to the image file.
If you are on Windows, prefix the path with r to mark it as a raw string.
Copied!image_path = r'C:\Users\Alice\Desktop\my-image.png'
How to Convert Image to Base64 String in Python
To convert the Image to Base64 String in Python, you can use the “base64.b64encode()” method that provides the b64encode() method. The base64.b64encode() function encodes a string using Base64 and returns that string.
Syntax
base64.b64encode(s[, altchars])
Parameters
s: It is an input and required parameter.
altchars: It 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 1: How to convert an 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)
I am getting the long string in the output in the terminal, like the following.
xrfaP11Zcs/PROUWCp7bOF7TZsPuAxAvWmY0EkyUZ+IF49r3aOEYbllIVB7mWkgXr88st9aZVx5+5jE+ ihdEZZFSaVUmJZhGNmVQzOxX7mrT//r2OHpHoQEO+G55O0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s6rbGrGT/ikQnOhVNnLimbbxVLeFS8tdm jVOE0wcmkOvu5nF3/apPPxXgEapMdnaqiKGbilvzadZFg503N+Pjyf/UNvhu7oXayGXKPg/F/zbZ6b0Oelqt 2f/bgOULOh4mSezS55a4pPLYdFCYi0sLtb3nwukE6J20uCqAfvretNh0+xyFpHt6j/+waFfxcDxzR1s4vY1D dGTn/GVld9rr2Udrf6pN4He6cMWQsw2Ow9fwzl6Og/tk7ZxVa/+h/+9z++2j73iJyXQ+ac+nJy7tinATA6y XOP9RTl8rJbTI/p69m3lsjWkqaTAXj49XV3zil73n4Y4pP6vjHdavM7+vk7MiwuGEZRtJa0KTQeu72y2EIC g9k83B7KAcGB9CVAZf8iiK9mxee7P3Qao3L+r/p3DYiXJ8t/SqtghnnP0sZQvr+bUtJtDpo9TAJUELKS0Es 3aPJ6nxVHuuwzt9pkynpqfqxcs4uncJBN0zcpMLrofEGBRWz2HNXO0J57woQfpXc1GHd1vTN4T2c8JtwBhj JC7pB7tn2MJ0/lpf+QWuCzMoUGMupPsAIj1x7y+ViO2aFxlP3qH+LLZJcv++B0kzYwmag38ljr9vudS2ZuKe c3utBQ4E/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 quotations.
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'))