save figure image to file
502041
def save_figure(self, event=None, panel='top'):
        
        panel = self.get_panel(panel)
        panel.save_figure(event=event)
712464
def _save_plot(self, *args, extension='pdf', **kwargs):
        
        import matplotlib.pyplot as plt

        tmp_path = make_temp_dir()
        filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.'))
        filepath = posixpath.join(tmp_path, filename)

        plt.savefig(filepath, *args, **kwargs)
        return filepath
782868
def save_img(self, file_name=None, file_type="gif", mode='dot'):
        '''
        
        '''

        if not file_name:
            warnings.warn(DeprecationWarning, "always pass a file_name")
            file_name = "out"

        if  mode == 'neato':
            self.save_dot(self.temp_neo)
            neato_cmd = "%s -o %s %s" % (self.neato, self.temp_dot, self.temp_neo)
            os.system(neato_cmd)
            plot_cmd = self.dot
        else:
            self.save_dot(self.temp_dot)
            plot_cmd = self.dot

        file_name  = "%s.%s" % (file_name, file_type)
        create_cmd = "%s -T%s %s -o %s" % (plot_cmd, file_type, self.temp_dot, file_name)
        os.system(create_cmd)
671544
def save_image(image, destination=None, filename=None, **options):
    
    if destination is None:
        destination = BytesIO()
    filename = filename or ''
    # Ensure plugins are fully loaded so that Image.EXTENSION is populated.
    Image.init()
    format = Image.EXTENSION.get(os.path.splitext(filename)[1].lower(), 'JPEG')
    if format in ('JPEG', 'WEBP'):
        options.setdefault('quality', 85)
    saved = False
    if format == 'JPEG':
        if image.mode.endswith('A'):
            # From PIL 4.2, saving an image with a transparency layer raises an
            # IOError, so explicitly remove it.
            image = image.convert(image.mode[:-1])
        if settings.THUMBNAIL_PROGRESSIVE and (
                max(image.size) >= settings.THUMBNAIL_PROGRESSIVE):
            options['progressive'] = True
        try:
            image.save(destination, format=format, optimize=1, **options)
            saved = True
        except IOError:
            # Try again, without optimization (PIL can't optimize an image
            # larger than ImageFile.MAXBLOCK, which is 64k by default). This
            # shouldn't be triggered very often these days, as recent versions
            # of pillow avoid the MAXBLOCK limitation.
            pass
    if not saved:
        image.save(destination, format=format, **options)
    if hasattr(destination, 'seek'):
        destination.seek(0)
    return destination
679124
def save_figure(self,event=None,panel=None):
        
        if panel is None: panel = self.current_panel
        self.panels[panel].save_figure(event=event)
602445
def save_all_figures_as(self):
        """"""
        self.redirect_stdio.emit(False)
        dirname = getexistingdirectory(self, caption='Save all figures',
                                       basedir=getcwd_or_home())
        self.redirect_stdio.emit(True)
        if dirname:
            return self.save_all_figures_todir(dirname)
942101
public static void savePng(Bitmap src, String fileName) throws ImageSaveException {
        save(src, fileName, Bitmap.CompressFormat.PNG, 100);
    }
770076
def file_to_png(fp):
	
	import PIL.Image # pylint: disable=import-error
	with io.BytesIO() as dest:
		PIL.Image.open(fp).save(dest, "PNG", optimize=True)
		return dest.getvalue()
26853
def _finalise_figure(fig, **kwargs):  # pragma: no cover
    
    title = kwargs.get("title") or None
    show = kwargs.get("show") or False
    save = kwargs.get("save") or False
    savefile = kwargs.get("savefile") or "EQcorrscan_figure.png"
    return_fig = kwargs.get("return_figure") or False
    if title:
        fig.suptitle(title)
    if show:
        fig.show()
    if save:
        fig.savefig(savefile)
        print("Saved figure to {0}".format(savefile))
    if return_fig:
        return fig
    return None
605705
def save_image(self, cat, img, data):
        """"""
        filename = self.path(cat, img)
        mkdir(filename)
        if type(data) == np.ndarray:
            data = Image.fromarray(data).convert('RGB')
        data.save(filename)
460676
def save_mag_to_file(mag, filename, rhofile):
    
    if rhofile:
        # bring data in shape
        null = np.zeros(len(mag))
        if mag.shape[1] == 3:
            null = np.column_stack((null, null, null, null))
        result = np.column_stack((mag, null))

        # save datapoints
        with open(filename, 'w') as fid:
            fid.write('{0}\n'.format(mag.shape[0]))
        with open(filename, 'ab') as fid:
            np.savetxt(fid, np.array(result), fmt='%f')

    else:
        # bring data in shape
        with open('inv/rho00.mag', 'r') as fid:
            coor = np.loadtxt(fid, skiprows=1, usecols=[0, 1])
        # calculated back to log
        if mag.shape[1] == 3:
            logx = [math.log(d, 10) for d in mag[:, 0]]
            logy = [math.log(d, 10) for d in mag[:, 1]]
            logz = [math.log(d, 10) for d in mag[:, 2]]
            mag_log = np.column_stack((logx, logy, logz))
        else:
            mag_log = [math.log(d, 10) for d in mag]
        content = np.column_stack((coor[:, 0], coor[:, 1], mag_log))

        # save datapoints
        with open(filename, 'w') as fid:
            fid.write('{0}\n'.format(content.shape[0]))
        with open(filename, 'ab') as fid:
            np.savetxt(fid, np.array(content), fmt='%f')
487086
def save_all_figures_todir(self, dirname):
        """"""
        fignames = []
        for thumbnail in self._thumbnails:
            fig = thumbnail.canvas.fig
            fmt = thumbnail.canvas.fmt
            fext = {'image/png': '.png',
                    'image/jpeg': '.jpg',
                    'image/svg+xml': '.svg'}[fmt]

            figname = get_unique_figname(dirname, 'Figure', fext)
            save_figure_tofile(fig, fmt, figname)
            fignames.append(figname)
        return fignames
634734
def save(self, delete_zip_import=True, *args, **kwargs):
        
        super(BaseGallery, self).save(*args, **kwargs)
        if self.zip_import:
            zip_file = ZipFile(self.zip_import)
            for name in zip_file.namelist():
                data = zip_file.read(name)
                try:
                    from PIL import Image
                    image = Image.open(BytesIO(data))
                    image.load()
                    image = Image.open(BytesIO(data))
                    image.verify()
                except ImportError:
                    pass
                except:
                    continue
                name = os.path.split(name)[1]

                # In python3, name is a string. Convert it to bytes.
                if not isinstance(name, bytes):
                    try:
                        name = name.encode('cp437')
                    except UnicodeEncodeError:
                        # File name includes characters that aren't in cp437,
                        # which isn't supported by most zip tooling. They will
                        # not appear correctly.
                        tempname = name

                # Decode byte-name.
                if isinstance(name, bytes):
                    encoding = charsetdetect(name)['encoding']
                    tempname = name.decode(encoding)

                # A gallery with a slug of "/" tries to extract files
                # to / on disk; see os.path.join docs.
                slug = self.slug if self.slug != "/" else ""
                path = os.path.join(GALLERIES_UPLOAD_DIR, slug, tempname)
                try:
                    saved_path = default_storage.save(path, ContentFile(data))
                except UnicodeEncodeError:
                    from warnings import warn
                    warn("A file was saved that contains unicode "
                         "characters in its path, but somehow the current "
                         "locale does not support utf-8. You may need to set "
                         "'LC_ALL' to a correct value, eg: 'en_US.UTF-8'.")
                    # The native() call is needed here around str because
                    # os.path.join() in Python 2.x (in posixpath.py)
                    # mixes byte-strings with unicode strings without
                    # explicit conversion, which raises a TypeError as it
                    # would on Python 3.
                    path = os.path.join(GALLERIES_UPLOAD_DIR, slug,
                                        native(str(name, errors="ignore")))
                    saved_path = default_storage.save(path, ContentFile(data))
                self.images.create(file=saved_path)
            if delete_zip_import:
                zip_file.close()
                self.zip_import.delete(save=True)
1206989
def save_figure_raw_data(figure="gcf", **kwargs):
    

    # choose a path to save to
    path = _s.dialogs.Save(**kwargs)
    if path=="": return "aborted."

    # if no argument was given, get the current axes
    if figure=="gcf": figure = _pylab.gcf()

    for n in range(len(figure.axes)):
        a = figure.axes[n]

        for m in range(len(a.lines)):
            l = a.lines[m]

            x = l.get_xdata()
            y = l.get_ydata()

            p = _os.path.split(path)
            p = _os.path.join(p[0], "axes" + str(n) + " line" + str(m) + " " + p[1])
            print(p)

            # loop over the data
            f = open(p, 'w')
            for j in range(0, len(x)):
                f.write(str(x[j]) + "\t" + str(y[j]) + "\n")
            f.close()
614036
def makeFigFromFile(filename,*args,**kwargs):
    
    import matplotlib.pyplot as plt
    img = plt.imread(filename)
    fig,ax = plt.subplots(*args,**kwargs)
    ax.axis('off')
    ax.imshow(img)
    return fig
382391
def save(filename, options = {})
      ps = send(@symbol)
      gs_options = [
        "-dBATCH", "-dNOPAUSE", "-q", "-dTextAlphaBits=4", "-dSAFER",
        "-sOutputFile=#{filename}",
        "-sDEVICE=pnggray"
      ]
      barcode_ps = "#{File.expand_path(File.dirname(__FILE__))}/barcode.ps"
      sub = Subexec.run "gs #{gs_options.join(" ")} #{barcode_ps} -c '#{ps}'"
      raise(GhostScriptError, sub.output) unless sub.exitstatus == 0
      resize_method = (ps =~ /includetext/ ? "-scale" : "-sample")
      im_options = ["-trim"]
      im_options += ["-bordercolor white", "-border 10%"] if options[:border] != false
      im_options << "#{resize_method} #{options[:width]}" if options[:width]
      sub = Subexec.run "mogrify #{im_options.join(' ')} #{filename}"
      raise(ImageMagickError, sub.output) unless sub.exitstatus == 0
      File.open(filename, 'r')
    end
890990
def to_file(self, filename):
        

        img = self.to_image()
        img.save(filename, optimize=True)
        return self