3

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?

Remotec
  • 10,304
  • 25
  • 105
  • 147

5 Answers5

4

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
Sankar guru
  • 935
  • 1
  • 7
  • 16
2

This code does the job:

from PIL import Image
import io
import base64
import cStringIO

image = Image.open(io.BytesIO(imagebuffer))
encodingbuffer = cStringIO.StringIO()
image.save(encodingbuffer, format="JPEG")
encodedimage = base64.b64encode(encodingbuffer.getvalue())
Remotec
  • 10,304
  • 25
  • 105
  • 147
0
  1. Save the img in a buffer - doesn't touch disk
  2. regex for jpeg headers and footers - fault tolerance ( Header: FF D8 FF, Footer: FF D9)
  3. base64 the data
  4. flush to file
RandomHash
  • 669
  • 6
  • 20
0

I`m working with .dwg file and Python 2.7, this works for me:

import os
import base64

# Open the file
infile = open(input_file, 'r')
# 'r' says we are opening the file to read, infile is the opened file object that we will read from
# encode file to base64
base64EncodedStr = base64.b64encode(infile.read())
Anna G
  • 1
  • 3
-1

Please try this to base64 encode an image using python

import base64

with open("test.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    print(encoded_string)

OR

import base64

image = open('test.jpeg', 'rb')
image_read = image.read()
image_encode = base64.b64encode(image_read)
print(image_encode)