Python 3

import base64
from io import BytesIO

buffered = BytesIO()
image.save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue())

Python 2

import base64
import cStringIO

buffer = cStringIO.StringIO()
image.save(buffer, format="JPEG")
img_str = base64.b64encode(buffer.getvalue())
Answer from Eugene V on Stack Overflow
🌐
CodoRaven
codoraven.com › home › image & base64 | opencv vs pillow | python
Image & Base64 | OpenCV vs Pillow | Python - CodoRaven
March 16, 2023 - This is widely used on the web and email to deliver data like images. import base64 with open("your_image.jpg", "rb") as f: base64_str = base64.b64encode(f.read()) import base64 from io import BytesIO from PIL import Image # Pillow to base64 ...
Discussions

python - Faster way to convert a PIL image into base64 - Stack Overflow
There are faster third-party modules for base64 en- and decoding if you look for them. For performance testing, you really need to provide a reference test image. ... I found pyvips to be 13x faster than PIL in a comparison here... More on stackoverflow.com
🌐 stackoverflow.com
python - How to convert Image PIL into Base64 without saving - Stack Overflow
I generate an image with Python, and I need to convert this Pil Image into a Base64, without saving this one into any folder... I have some data, and I get RGB img with the line below: img = Image. More on stackoverflow.com
🌐 stackoverflow.com
Convert image to base64 using python PIL - Stack Overflow
the following code is throwing an error Error with file: string argument expected, got 'bytes' I also tried using BytesIO but it threw an error about needed a format of string and not bytes. Very More on stackoverflow.com
🌐 stackoverflow.com
python - How to get a PIL image as a Base64 encoded string - Stack Overflow
for the past few hours i've been trying to create a Base64 String of an Image, but it won't work. ship_color = (0,100,100,255) img = Image.new("RGBA", (100,100)) for i in range(20): for j in ra... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

Can I use PIL with Python 2 for image processing?
A: Yes, but you should consider upgrading to Python 3 since Python 2 is no longer officially supported. PIL has been replaced by Pillow, which is compatible with Python 3.
🌐
sqlpey.com
sqlpey.com › python › top-4-methods-to-convert-pil-image-to-base64-string
Top 4 Methods to Convert PIL Image to Base64 String - sqlpey
What is the purpose of Base64 encoding images?
A: Base64 encoding converts binary data into a textual format, making it easier to transmit over protocols that may not support binary data directly.
🌐
sqlpey.com
sqlpey.com › python › top-4-methods-to-convert-pil-image-to-base64-string
Top 4 Methods to Convert PIL Image to Base64 String - sqlpey
How do I rotate an image in Python using Pillow?
A: You can rotate an image using the rotate() method from the Pillow library. Specify the angle you want to rotate your image.
🌐
sqlpey.com
sqlpey.com › python › top-4-methods-to-convert-pil-image-to-base64-string
Top 4 Methods to Convert PIL Image to Base64 String - sqlpey
🌐
C# Corner
c-sharpcorner.com › article › converting-image-to-base64-in-python
Converting Image To Base64 In Python
March 16, 2023 - In this article, we have learned how to convert an image to base64 format in Python using the Pillow and base64 modules. Encoding an image in base64 format can transfer it over the internet or store it in a text file.
🌐
sqlpey
sqlpey.com › python › top-4-methods-to-convert-pil-image-to-base64-string
Top 4 Methods to Convert PIL Image to Base64 String - sqlpey
November 23, 2024 - To convert your rotated_image back to a Base64 string, you can follow these methods: First, ensure you have the required libraries available. Install Pillow if you haven’t already:
🌐
jdhao's digital space
jdhao.github.io › 2020 › 03 › 17 › base64_opencv_pil_image_conversion
Conversion between base64 and OpenCV or PIL Image · jdhao's digital space
May 7, 2021 - im_b64 = base64.b64encode(im_bytes) In the above code, instead of saving the PIL Image object img to the disk, we save it to im_file which is a file-like object.
🌐
Reddit
reddit.com › r/pythonprojects2 › how to convert image to base64 in python?
r/PythonProjects2 on Reddit: How to convert image to base64 in Python?
October 27, 2024 - First, we need to use the base64 module. Since it’s a built-in library, you don’t have to install anything separately. ... The next step is to open the image file that you want to convert.
Top answer
1 of 2
2

As suggested in the comments, I tried pyvips as below:

#!/usr/bin/env python3
import requests
import base64
import numpy as np
from PIL import Image
from io import BytesIO
from cv2 import imencode
import pyvips

def vips_2PNG(image,compression=6):
    # Convert PIL Image to Numpy array
    na = np.array(image)
    height, width, bands = na.shape

    # Convert Numpy array to Vips image
    dtype_to_format = {
       'uint8': 'uchar',
       'int8': 'char',
       'uint16': 'ushort',
       'int16': 'short',
       'uint32': 'uint',
       'int32': 'int',
       'float32': 'float',
       'float64': 'double',
       'complex64': 'complex',
       'complex128': 'dpcomplex',
    }
    linear = na.reshape(width * height * bands)
    vi = pyvips.Image.new_from_memory(linear.data, width, height, bands,dtype_to_format[str(na.dtype)])

    # Save to memory buffer as PNG
    data = vi.write_to_buffer(f".png[compression={compression}]")
    return data

def vips_including_reading_from_disk(image):
    # Load image from disk
    image = pyvips.Image.new_from_file('stuttgart.png', access='sequential')
    # Save to memory buffer as PNG
    data = image.write_to_buffer('.png')
    return data

def faster(image):
    image_arr = np.array(image)
    _, byte_data = imencode('.png', image_arr)        
    return byte_data

def orig(image, faster=True):    
    output_buffer = BytesIO()
    image.save(output_buffer, format='PNG')
    byte_data = output_buffer.getvalue()
    return byte_data

# img_url = "https://www.cityscapes-dataset.com/wordpress/wp-content/uploads/2015/07/stuttgart03.png"
filename = 'stuttgart.png'
img = Image.open(filename)

# r = orig(img)
# print(len(r))
# %timeit r = orig(img)

# r = faster(img)
# print(len(r))
# %timeit r = faster(img)

# r = vips_including_reading_from_disk(filename)
# print(len(r))
# %timeit r = vips_including_reading_from_disk(filename)

# r = vips_2PNG(img,0)
# print(len(r))
# %timeit r = vips_2PNG(img,0)

I was looking at trading off the compression parameter between file size and speed. Here is what I got - I wouldn't compare absolute values, but rather look at the performance relative to each other on my machine:

               Filesize        Time
PIL            1.7MB           1.12s
OpenCV         2.0MB           173ms   <--- COMPARE
vips(comp=0)   6.2MB           66ms
vips(comp=1)   2.0MB           132ms   <--- COMPARE
vips(comp=2)   2.0MB           153ms

I have put arrows next to the ones I would compare.

2 of 2
1

I use cv2.imencode which is 5x faster than before. Here's the code

import time
import requests
import base64
import numpy as np
from PIL import Image
from io import BytesIO
from cv2 import imencode


# input: single PIL image
def image_to_base64(image, faster=True):    
    now_time = time.time()
    if faster:        
        image_arr = np.array(image)
        _, byte_data = imencode('.png', image_arr)        
        print('--imencode: ' + str(time.time()-now_time))
    else:
        output_buffer = BytesIO()
        image.save(output_buffer, format='PNG')
        byte_data = output_buffer.getvalue()
        print('--image.save:' + str(time.time()-now_time))

    now_time = time.time()
    encoded_input_string  = base64.b64encode(byte_data)
    print('--base64.b64encode: ' + str(time.time()-now_time))

    now_time = time.time()
    input_string = encoded_input_string.decode("utf-8")
    print('--encoded_input_string.decode: ' + str(time.time()-now_time))  

    return input_string

img_url = "https://www.cityscapes-dataset.com/wordpress/wp-content/uploads/2015/07/stuttgart03.png"
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
now_time = time.time()
input_string = image_to_base64(img, faster=True)
print('total: ' + str(time.time()-now_time))

I wonder if there is any solution which can run faster.

Find elsewhere
🌐
YouTube
youtube.com › hey delphi
PYTHON : How to convert PIL Image.image object to base64 string? - YouTube
PYTHON : How to convert PIL Image.image object to base64 string?To Access My Live Chat Page, On Google, Search for "hows tech developer connect"As promised, ...
Published   April 20, 2023
Views   117
🌐
GitHub
gist.github.com › WFT › 8643677
base64 PIL processing · GitHub
Save WFT/8643677 to your computer and use it in GitHub Desktop. Download ZIP · base64 PIL processing · Raw · b64_image_utils.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
YouTube
youtube.com › luke chaffey
How to get a PIL image as a Base64 encoded string - YouTube
python: How to get a PIL image as a Base64 encoded stringThanks for taking the time to learn more. In this video I'll go through your question, provide vario...
Published   July 31, 2023
Views   31
Top answer
1 of 2
17

Here's a short but complete demo of your code using a ByteIO instead of StringIO. I've also added a function to do the reverse conversion. It runs correctly on Python 2.6 and 3.6. The only difference is that in Python 3 the Base64 output is a b string.

from PIL import Image
from io import BytesIO
import base64

# Convert Image to Base64 
def im_2_b64(image):
    buff = BytesIO()
    image.save(buff, format="JPEG")
    img_str = base64.b64encode(buff.getvalue())
    return img_str

# Convert Base64 to Image
def b64_2_img(data):
    buff = BytesIO(base64.b64decode(data))
    return Image.open(buff)

# Test

img = Image.new('RGB', (120, 90), 'red')
img.show()

img_b64 = im_2_b64(img)
print(img_b64)

new_img = b64_2_img(img_b64)
new_img.show()

Python 3 output

b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABaAHgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDi6KKK+ZP3EKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9k='
2 of 2
-1

You can use this function to convert an image to base64 string.

import base64

def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
        return encoded_string

base64String = image_to_base64('image.jpg')
🌐
Bobby Hadz
bobbyhadz.com › blog › convert-image-to-base64-string-in-python
Convert an Image to Base64 String and vice versa in Python | bobbyhadz
April 11, 2024 - Copied!import io import base64 from PIL import Image with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) base64_string = base64_bytes.decode() img = Image.open( io.BytesIO( base64.decodebytes(bytes(base64_string, 'utf-8')) ) ) img.save('house2.webp') We convert the base64 string to an image and save it using the Image.save() method...
🌐
CodeSpeedy
codespeedy.com › home › convert image to base64 string in python
Convert Image to Base64 String in Python - CodeSpeedy
September 19, 2023 - ... At first, we opened our file in ‘rb’ mode. Then we read the image file and encoded it with the following line: base64.b64encode(img_file.read()) – b64encode() is a method to encode the data into base64
🌐
Google Groups
groups.google.com › a › tensorflow.org › g › swift › c › 8qhWR8dOa5E
PIL Image to NSImage
March 1, 2021 - I my case the Swift code call python function using PythonKit.The Python function return PIL image. For now I use base64 encode/decode to convert PIL image to base64 string and from swift side convert base64 string to NSImage.But it's a slow way to get image.
🌐
DEV Community
dev.to › bl4ckst0n3 › image-processing-how-to-read-image-from-string-in-python-pf8
Image Processing: How to read image from string in python ? - DEV Community
August 26, 2021 - Python base64 module is also used for this process. Let's start with importing the required modules. ... That's it ! So, the first we are going to convert image to base64 using python. Let's do it !
🌐
NodePit
nodepit.com › scripting _ py script _ convert pil image object to base64 string
Scripting _ Py Script _ Convert PIL Image Object to base64 String — NodePit
October 1, 2024 - https://forum.knime.com/t/image-column-access-meta-data-in-python-extension/83024/ · To use this workflow in KNIME, download it from the below URL and open it in KNIME:
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-image-to-string-and-vice-versa
Python - Convert Image to String and vice-versa - GeeksforGeeks
July 23, 2025 - To convert an image to a string in Python, we can turn the image into a special text format called base64. This allows us to store or send the image as text which is easier to handle in some situations.