title: How to base64 encode an image using python
body: <p>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.</p>
  
  <p>My Python 2.7 code so far looks like this:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I can see I have the image I want and can save it to the disk in jpeg format.</p>
  
  <p>What I don't understand is if I can base64 encode the image from the <code>image</code> object or if I need to write it to the disk first. I would like to avoid writing it if possible.</p>
  
  <p>The 2nd question I have is what is <code>PIL</code> 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 <em>yes</em> as I can change the file extension to <code>.bmp</code> and the correct file is written on the disk.</p>
  
  <p>So in summary, is it possible to get a base64 encoded version of my jpeg file from the <code>image</code> object without writing it to disk first?</p>