'**SUMMARY**
Save the image to the specified filename.  If no filename is provided then
then it will use the filename the Image was loaded from or the last
place it was saved to. You can save to lots of places, not just files.
For example you can save to the Display, a JpegStream, VideoStream,
temporary file, or Ipython Notebook.
Save will implicitly render the image\'s layers before saving, but the layers are
not applied to the Image itself.
**PARAMETERS**
* *filehandle_or_filename* - the filename to which to store the file. The method will infer the file type.
* *mode* - This flag is used for saving using pul.
* *verbose* - If this flag is true we return the path where we saved the file.
* *temp* - If temp is True we save the image as a temporary file and return the path
* *path* - path where temporary files needed to be stored
* *filename* - name(Prefix) of the temporary file.
* *cleanTemp* - This flag is made True if tempfiles are tobe deleted once the object is to be destroyed.
* *params* - This object is used for overloading the PIL save methods. In particular
this method is useful for setting the jpeg compression level. For JPG see this documentation:
http://www.pythonware.com/library/pil/handbook/format-jpeg.htm
**EXAMPLES**
To save as a temporary file just use:
>>> img = Image(\'simplecv\')
>>> img.save(temp=True)
It will return the path that it saved to.
Save also supports IPython Notebooks when passing it a Display object
that has been instainted with the notebook flag.
To do this just use::
>>> disp = Display(displaytype=\'notebook\')
>>> img.save(disp)
.. Note::
You must have IPython notebooks installed for this to work path and filename are valid if and only if temp is set to True.
.. attention::
We need examples for all save methods as they are unintuitve.'

def save(self, filehandle_or_filename='', mode='', verbose=False, temp=False, path=None, filename=None, cleanTemp=False, **params):

    if temp:
        import glob
        if (filename == None):
            filename = 'Image'
        if (path == None):
            path = tempfile.gettempdir()
        if glob.os.path.exists(path):
            path = glob.os.path.abspath(path)
            imagefiles = glob.glob(glob.os.path.join(path, (filename + '*.png')))
            num = [0]
            for img in imagefiles:
                num.append(int(glob.re.findall('[0-9]+$', img[:(-4)])[(-1)]))
            num.sort()
            fnum = (num[(-1)] + 1)
            filename = glob.os.path.join(path, ((filename + ('%07d' % fnum)) + '.png'))
            self._tempFiles.append((filename, cleanTemp))
            self.save(self._tempFiles[(-1)][0])
            return self._tempFiles[(-1)][0]
        else:
            print 'Path    does    not    exist!'
    elif filename:
        filehandle_or_filename = (filename + '.png')
    if (not filehandle_or_filename):
        if self.filename:
            filehandle_or_filename = self.filename
        else:
            filehandle_or_filename = self.filehandle
    if len(self._mLayers):
        saveimg = self.applyLayers()
    else:
        saveimg = self
    if ((self._colorSpace != ColorSpace.BGR) and (self._colorSpace != ColorSpace.GRAY)):
        saveimg = saveimg.toBGR()
    if (not isinstance(filehandle_or_filename, basestring)):
        fh = filehandle_or_filename
        if (not PIL_ENABLED):
            logger.warning('You    need    the    python    image    library    to    save    by    filehandle')
            return 0
        if ((type(fh) == InstanceType) and (fh.__class__.__name__ == 'JpegStreamer')):
            fh.jpgdata = StringIO()
            saveimg.getPIL().save(fh.jpgdata, 'jpeg', **params)
            fh.refreshtime = time.time()
            self.filename = ''
            self.filehandle = fh
        elif ((type(fh) == InstanceType) and (fh.__class__.__name__ == 'VideoStream')):
            self.filename = ''
            self.filehandle = fh
            fh.writeFrame(saveimg)
        elif ((type(fh) == InstanceType) and (fh.__class__.__name__ == 'Display')):
            if (fh.displaytype == 'notebook'):
                try:
                    from IPython.core.display import Image as IPImage
                except ImportError:
                    print 'You    need    IPython    Notebooks    to    use    this    display    mode'
                    return
                from IPython.core import display as Idisplay
                tf = tempfile.NamedTemporaryFile(suffix='.png')
                loc = tf.name
                tf.close()
                self.save(loc)
                Idisplay.display(IPImage(filename=loc))
                return
            else:
                self.filehandle = fh
                fh.writeFrame(saveimg)
        else:
            if (not mode):
                mode = 'jpeg'
            try:
                saveimg.getPIL().save(fh, mode, **params)
                self.filehandle = fh
                self.filename = ''
                return 1
            except Exception as e:
                if (mode.lower() != 'webp'):
                    raise e
        if verbose:
            print self.filename
        if (not (mode.lower() == 'webp')):
            return 1
    if (not filehandle_or_filename):
        filename = tempfile.mkstemp(suffix='.png')[(-1)]
    else:
        filename = filehandle_or_filename
    if ((mode == 'webp') or re.search('\\.webp$', filename)):
        try:
            self.getPIL().save(filename, **params)
        except:
            try:
                from webm import encode as webmEncode
                from webm.handlers import BitmapHandler, WebPHandler
            except:
                logger.warning('You    need    the    webm    library    to    save    to    webp    format.    You    can    download    from:    https://github.com/sightmachine/python-webm')
                return 0
            PNG_BITMAP_DATA = bytearray(self.toString())
            IMAGE_WIDTH = self.width
            IMAGE_HEIGHT = self.height
            image = BitmapHandler(PNG_BITMAP_DATA, BitmapHandler.RGB, IMAGE_WIDTH, IMAGE_HEIGHT, (IMAGE_WIDTH * 3))
            result = webmEncode.EncodeRGB(image)
            if (filehandle_or_filename.__class__.__name__ == 'StringIO'):
                filehandle_or_filename.write(result.data)
            else:
                file(filename.format('RGB'), 'wb').write(result.data)
            return 1
    if params:
        if (not mode):
            mode = 'jpeg'
        saveimg.getPIL().save(filename, mode, **params)
        return 1
    if filename:
        cv.SaveImage(filename, saveimg.getBitmap())
        self.filename = filename
        self.filehandle = ''
    elif self.filename:
        cv.SaveImage(self.filename, saveimg.getBitmap())
    else:
        return 0
    if verbose:
        print self.filename
    if temp:
        return filename
    else:
        return 1
