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 def pil_to_base64(pil_img): img_buffer = BytesIO() pil_img.save(img_buffer, format='JPEG') byte_data = img_buffer.getvalue() base64_str = base64.b64encode(byte_data) return base64_str # base64 to Pillow def base64_to_pil(base64_str): pil_img = base64.b64decode(base64_str) pil_img = BytesIO(pil_img) pil_img = Image.open(pil_img) return pil_img
Discussions

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
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
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 - Decoding base64 from POST to use in PIL - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow. 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 - Once you have installed the Pillow module, you can load the image that you want to encode in base64 format using the Image module.
🌐
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.
🌐
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.
🌐
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.
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
🌐
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 - I have used the other function inside this function to get image string and the other function returns image string as you know. Anyways so base64_string variable holds image string in base64 format and decoded. The last I have used Image function ...
🌐
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 - Explore effective ways to convert a PIL Image object to a Base64 string in Python, including sample codes and alternative methods.
🌐
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
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.

🌐
Medium
medium.com › @maggi.giuseppe › python-embedding-images-in-json-objects-with-base64-8579059d80d7
Python: embedding images in JSON objects with base64 | by Giuseppe Maggi | Medium
March 12, 2024 - In fact, we get the value of content of the first element in the images list: from io import BytesIO import base64, json from PIL import Image with open('embedded.json', 'r') as f: data_received=json.load(f) im = Image.open(BytesIO(base64.b...
🌐
Jianshu
jianshu.com › p › 2ff8e6f98257
PIL.Image与Base64 String的互相转换 - 简书
January 18, 2018 - import base64 from io import BytesIO # pip3 install pillow from PIL import Image # 若img.save()报错 cannot write mode RGBA as JPEG # 则img = Image.open(image_path).convert('RGB') def image_to_base64(image_path): img = Image.open(image_path) output_buffer = BytesIO() img.save(output_buffer, format='JPEG') byte_data = output_buffer.getvalue() base64_str = base64.b64encode(byte_data) return base64_str
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')
🌐
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
🌐
KNIME Community Hub
hub.knime.com › gonhaddock › spaces › Public › Scripting _ Py Script _ Convert PIL Image Object to base64 String~ZdJBVe0oZYaGi504 › current-state
Scripting _ Py Script _ Convert PIL Image Object to base64 String – KNIME Community Hub
October 3, 2024 - https://forum.knime.com/t/image-column-access-meta-data-in-python-extension/83024/ Loading deploymentsLoading manual runs ... Created with KNIME Analytics Platform version 4.7.2 Note: Not all extensions may be displayed. ... By using or downloading the workflow, you agree to our terms and conditions.
🌐
Tech Coil
techcoil.com › blog › how-to-use-python-3-to-convert-your-images-to-base64-encoding
How to use Python 3 to convert your images to Base64 encoding
May 11, 2020 - Once we have done so, we define a function, get_base64_encoded_image, that takes an image path as the parameter.