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
🌐
PyPI
pypi.org › project › img64
img64 · PyPI
This library converts images to base64 encoding and vice versa. ... from PIL import Image import cv2 import img64 # PIL image to Base64 image = Image.open('sample.png') base64 = img64.image_to_base64(image) base64[:30] # 'iVBORw0KGgoAAAANSU...
Discussions

python - Faster way to convert a PIL image into base64 - Stack Overflow
#!/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 ... 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
September 19, 2018
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
January 14, 2018
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
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
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
🌐
CodoRaven
codoraven.com › home › image & base64 | opencv vs pillow | python
Image & Base64 | OpenCV vs Pillow | Python - CodoRaven
March 16, 2023 - 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
🌐
C# Corner
c-sharpcorner.com › article › converting-image-to-base64-in-python
Converting Image To Base64 In Python
March 16, 2023 - In the above example, we read the image file in binary mode using the "rb" mode, and then we used the "b64encode" function from the "base64" module to convert the image to base64 format.
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.

🌐
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:
Top answer
1 of 2
18

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')
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
🌐
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.
🌐
Jianshu
jianshu.com › p › 2ff8e6f98257
PIL.Image与Base64 String的互相转换 - 简书
January 18, 2018 - py3: python3中没有cStringIO,对应的是io,但却不能使用io.StringIO来处理图片,它用来处理文本的IO操作,处理图片的应该是io.BytesIO · 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 ·
🌐
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 - Converting an image to Base64 is straightforward in Python, and you don’t need any external libraries because Python provides everything through its built-in base64 module.
🌐
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 - ... However, using a single backslash is not valid because the backslash character is used as an escape character and not as a separator of path components. You can also use the Pillow module to convert an image to a base64-encoded ...
🌐
Crashlaker
crashlaker.github.io › python › 2020 › 08 › 26 › image_encode_decode_base64.html
Image encode/decode base64 - Carlos Aguni Personal Blog
August 26, 2020 - #https://stackoverflow.com/questions/48229318/how-to-convert-image-pil-into-base64-without-saving/48229407 #ty @Taha Mahjoubi def img_to_base64_str(img): buffered = io.BytesIO() img.save(buffered, format="PNG") buffered.seek(0) img_byte = buffered.getvalue() img_str = "data:image/png;base64," + base64.b64encode(img_byte).decode() return img_str def img_from_base64_str(msg): msg = msg.replace("data:image/png;base64,", "") msg = base64.b64decode(msg) buf = io.BytesIO(msg) img = Image.open(buf) return img #https://stackoverflow.com/questions/38061267/matplotlib-graphic-image-to-base64 def plot_ba
🌐
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 from PIL to show image.
🌐
GitHub
gist.github.com › WFT › 8643677
base64 PIL processing · GitHub
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. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
GitHub
gist.github.com › aspose-com-gists › efc06400b0b5e15918b2f302ff88cd0e
Convert Image to Base64 in Python · GitHub
Convert Image to Base64 in Python. GitHub Gist: instantly share code, notes, and snippets.