Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base64 encode an image using python

I have a stream of data that comes from a device and I need to convert it into a jpeg and then base64 encode it to transfer it over the network.

My Python 2.7 code so far looks like this:

from PIL import Image
import io

image = Image.open(io.BytesIO(self.imagebuffer)) # Image buffer contains the image data from the device.
image.save("test.jpg") # Writes the image to the disk in jpeg format
image.show() # Opens the image using the OS image view

I can see I have the image I want and can save it to the disk in jpeg format.

What I don't understand is if I can base64 encode the image from the image object or if I need to write it to the disk first. I would like to avoid writing it if possible.

The 2nd question I have is what is PIL doing in this process? Is it taking the data and putting the required special codes into the file to make it a jpeg file? I think the answer tot his is yes as I can change the file extension to .bmp and the correct file is written on the disk.

So in summary, is it possible to get a base64 encoded version of my jpeg file from the image object without writing it to disk first?

like image 573
Remotec Avatar asked Apr 06 '26 03:04

Remotec


1 Answers

Try this code

Image base64 encoded format

Python code:

import os
import base64

image = 'test.jpg'

encoded_string = ""
with open(image, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    file = encoded_string
like image 66
Sankar guru Avatar answered Apr 08 '26 17:04

Sankar guru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!