Fast IN memory image with PIL and StringIO for fast processing

PIL is a powerfull Image library for Python.
I'm using PIL to manipulate and process camera footage on cambackup.

def get_footage_from_memory(self, data, timeOut=5, format="jpeg"):  
    url = self.__urlBuilder(data) + self.__cameraUrlBuilder(data)
    try:
      buffer = StringIO.StringIO()
      footage_mem = StringIO.StringIO()
      image = urllib2.urlopen(url, timeout=timeOut)
      # write image in the memory
      buffer.write(image.read())
      buffer.seek(0)
      im = Image.open(buffer)
      draw = ImageDraw.Draw(im)
      draw.text((0, 0), str(time.ctime()) + " Camera : " + str(data['slug']) , (255, 255, 255))
      buffer.close()
      im.save(footage_mem,'jpeg',quality=30)
      footage_mem.seek(0)
      return footage_mem


      collFootage.insert({'owner': User().username, 'retrieveid': retrieveid, 'imagefilename': imageFile.name})
      self.filename = imageFile.name
      return {'status': 'success', 'retrieveid': retrieveid}

    except Exception, e:
      return 'error ' + str(e)

This small code does all that awesome Job very fast.
Ok realy small ??
let me take only the part "that does it all"

StringIO  

StringIO is a module that behaves as a file but in memory.
StringIO Python documentation

the first part is to import that module

import StringIO  

I give the file in memory object variable buffer.

buffer = StringIO.StringIO()  

now we have a file in memory.
StringIO() is a function inside StringIO

In the example above I'm creating two StringIO objects

buffer = StringIO.StringIO()  
footage_mem = StringIO.StringIO()  
image = urllib2.urlopen(url, timeout=timeOut)  

now let's write to the object as of you are writing to a file object

      buffer.write(image.read())

important you need to go at the beging of the file so you can read it again

buffer.seek(0)  

now read it

im = Image.open(buffer)  

Do your thing with PIL

      draw = ImageDraw.Draw(im)
      draw.text((0, 0), str(time.ctime()) + " Camera : " + str(data['slug']) , (255, 255, 255))

important Close the object to avoid memory leaking You must close it otherwise the memory will stay in use.

buffer.close()  

Note that one if the objects are still open.
You will not see me close it here because I'm using it in my response object I will close it there.

Save the PIL image

im.save(footage_mem,'jpeg',quality=30)  

let's go to the beginning of the file so I can read it later

footage_mem.seek(0)  

Here I will return the StringIO object to my response object it will close it automatically for me.
ensure you are closing it after you read it.

return footage_mem  

Note :
StringIO are powerfull and awesome at the sametime.
but if you use them incorectly you will end up rebooting your system, because your memory will be full!