Python pil image to base64

Convert image to base64 using python PIL

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=' 

PM 2Ring 52918

  • Convert HTML string to image data and display it as an image in a template using Python
  • how to connect to a printer and print a png image using python and PIL library in Ubuntu
  • How to convert PIL image to wximage in Python 3
  • Convert sRGB image to grayscale using OpenImageIO and Python
  • Is there a way to draw the «REPLACEMENT CHARACTER» symbol on an image using cv2 or PIL in Python
  • convert image into pixel dataframe into csv file using python
  • convert HTML to json in python using BeautifulSoup
  • How can I convert complex .mat file to csv using python
  • How to Convert the text into Json Format using Python
  • How to propertly convert a base64 string to a image file?
  • How to convert and over write MongoDB date string into ISODate using Python PyMongo?
  • Loading image from a remote server in pyglet or PIL / python
  • using python to convert datetime to integer for NVD3 plotting
  • How to convert digits in a string into words using Python NLTK?
  • how to count black and white pixels in binary image using python
  • How to get on screen image coordinates using pyautogui in python 2.7
  • Detect object in an image using openCV python on a raspberry pi
  • How to open the image path if there are some image cannot open? PIL python
  • how to use opencv to convert an image into a matrix in Python
  • Display IR image from XBOX 360 using Open Kinect via Python and OpenCV
  • convert a fasta file to a tab-delimited file using python script
  • Using Python to edit the timestamps in a list? Convert POSIX to readable format using a function
  • Calculating Energy of image frame using DWT in python shows wrong value
  • how to convert a RGB image to its YIQ components in python , and then apply dct transform to compress it?
  • Convert a multi-threaded Python to a multi-process one using concurrent futures
  • Saving image element using splinter python
  • How to translate a small section of an image using OpenCV in Python
  • To detect digits from an image using cv2 and python
  • OSError: cannot identify image file I can’t get rid off the Thumb.db using Pillow in Python
  • How can I insert a widget on a background image using Gtk3 in python 3.4?
  • Image warping by means of a vector field using Python
  • How to convert a 24 color bmp image to 16 color bmp in python
  • Yodlee: Unable to convert image bytes to captcha in getMFAResponseForSite — Python
  • Using FLAC decoder and LAME Encoder to convert FLAC files using Python
  • Representing a Fan Shaped Image on a Map using Python
  • Different image using OpenCV in python and java
  • Image transmission and reception over usb port using python
  • How to install PIL programmatically using python script
  • Convert Access application from MDB (2000) to ACCDB (2007/2010) using Python
  • Evaluate image in html table using Python
  • Convert C# to Python using AES/CBC/NoPadding
  • Python — plotting different coloured clusters using PIL
  • how to store an image on Google Cloud Storage sent by Android using Python
  • Cannot upload image in selenium using python
  • Downloading image from URL using Python giving corrupted results
  • Traceback error with Python when using ffmpeg to convert a video
  • Convert python dictionary to xml string without using build-in functions
  • Uploading an image to GDrive using API — Python
  • Python image resizing, installing PIL
  • Python PIL save image after rotating
Читайте также:  Python set exit code

More Query from same tag

  • Retrieve multiple objects with presigned URL from S3 python
  • Getting Validation Accuracy of 99% with MNIST with less than 10000 parameters CNN
  • How can I avoid explicit decoding of content?
  • Flickering Sprite in Pygame
  • Python logging won’t write to file
  • Strange behaviour in dask apply with loop of lambda functions
  • Reading the next line of a file
  • Pie chart from highcharts does not render via justpy
  • Using one socket in UDP chat using threading
  • Printing the results of a function into a tkinter message box?
  • Python-Tkinter: Trying to unpack a button with an if statement
  • TypeError: argument 1 must be pygame .Surface, not button
  • Avoid being recognized as spam
  • python argparse -h like behaviour and mutually exclusive arguments
  • Maya Python: Getting a Float Slider Group to align in the same row as Checkboxes
  • sqlite3 function inside python program
  • How to save/change text of ‘QLineEdit’ in ‘QSettings’ and get on ‘QPushButton’s’ call
  • Print specific lines from a text file in python
  • Sending a message between HTML and python on the raspberry pi
  • Getting list of keys in Python dictionary whose dict-values are minimal according to a defined order
  • Draw points connected by spiral on a sphere with Matplotlib
  • I am creating a dict from a file with duplicate values. How do I prevent my loop overwriting existing values?
  • Why does Selenium run slower if the mouse is on the primary monitor with the browser session
  • How can I link MacPort’s pyqt to Enthought’s Python distribution?
  • png images with transparent background don’t work in pygame 2.0.0
  • «slice indices must be integers» error when splitting a data array
  • How do i get the full strings with a RegEx search in python that only captures part of the word?
  • How do I tell OSX to use matplotlib from brew, rather than default?
  • How can I request a URL that is already URL-encoded in python-requests?
  • How can I compare a value from database to python input
  • how to save redirection url to csv file in python
  • I am trying to convert hinglish dataset to english using python
  • Is there a way in python, I can create a function that concatenate the result of dataframe function to one dataframe
  • Kivy screenmanager «No Screen with name» error when redirecting
  • Selenium loads profile only in the deprecated way (Python)
Читайте также:  Date with time zone java

Источник

Conversion between base64 and OpenCV or PIL Image

When we are building web services using Python, we often send or receive images in base64 encoded format. However, when we are doing image processing tasks, we need to use PIL or OpenCV. In this post, I will share how to convert between OpenCV or PIL image and base64 encoded image.

base64 to PIL or OpenCV image

base64 to PIL Image

In the above code, since Image.open() only accepts image path or file-like object, we first convert the base64 encoded image to BytesIO object and then read the image using PIL.

base64 to OpenCV Image

 In the above code, we first convert binary image to Numpy array, then decode the array with cv2.imdecode() . The final img is an OpenCV image in Numpy ndarray format.

PIL or OpenCV image to base64

PIL Image to base64

 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. Note that in this case, we need to specify the image format in img.save() .

OpenCV to base64 image

 In the above code, we first save the image in Numpy ndarray format to im_arr which is a one-dim Numpy array. We then get the image in binary format by using the tobytes() method of this array.

References

Источник

Python pil image to base64

Last updated: Jun 23, 2023
Reading time · 4 min

banner

# Table of Contents

# Convert an Image to a Base64-encoded String in Python

To convert an image to a base64 string in Python:

  1. Use the with open() statement to open the image file.
  2. Use the file.read() method to read the image’s contents.
  3. 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)

convert image to base64 string in python

The code sample assumes that you have the following house.webp image in the same directory as your Python script.

house

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'

Источник

Оцените статью