Save frames of the videos into files.
165204
def save_video(video, save_path_template):
  """"""
  try:
    from PIL import Image  # pylint: disable=g-import-not-at-top
  except ImportError as e:
    tf.logging.warning(
        "Showing and saving an image requires PIL library to be "
        "installed: %s", e)
    raise NotImplementedError("Image display and save not implemented.")

  for i, frame in enumerate(video):
    save_path = save_path_template.format(i)
    with tf.gfile.Open(save_path, "wb") as sp:
      Image.fromarray(np.uint8(frame)).save(sp)
1200834
def frame_generator(self):
        """"""
        if self.input_rate == self.RATE_PROCESS:
            while True:
                yield self.read()
        else:
            while True:
                yield self.read_resampled()
1053040
def prepare_blobs(self):
        """"""
        self.raw_header = self.extract_header()
        if self.cache_enabled:
            self._cache_offsets()
720313
def write_multi(self, frames, encoded_frames=None):
    """"""
    if encoded_frames is None:
      # Infinite iterator.
      encoded_frames = iter(lambda: None, 1)
    for (frame, encoded_frame) in zip(frames, encoded_frames):
      self.write(frame, encoded_frame)
550505
def _update_frames(self, written):
        """"""
        if self.seekable():
            curr = self.tell()
            self._info.frames = self.seek(0, SEEK_END)
            self.seek(curr, SEEK_SET)
        else:
            self._info.frames += written
831709
def save_images(self):
        
        res_dict = self.treeview.get_selected()
        clobber = self.settings.get('clobber', False)
        self.treeview.clear_selection()  # Automatically disables Save button

        # If user gives empty string, no suffix.
        if self.suffix:
            sfx = '_' + self.suffix
        else:
            sfx = ''

        # Also include channel name in suffix. This is useful if user likes to
        # open the same image in multiple channels.
        if self.settings.get('include_chname', True):
            sfx += '_' + self.chname

        # Process each selected file. Each can have multiple edited extensions.
        for infile in res_dict:
            f_pfx = os.path.splitext(infile)[0]  # prefix
            f_ext = '.fits'  # Only FITS supported
            oname = f_pfx + sfx + f_ext
            outfile = os.path.join(self.outdir, oname)

            self.w.status.set_text(
                'Writing out {0} to {1} ...'.format(shorten_name(infile, 10),
                                                    shorten_name(oname, 10)))
            self.logger.debug(
                'Writing out {0} to {1} ...'.format(infile, oname))

            if os.path.exists(outfile) and not clobber:
                self.logger.error('{0} already exists'.format(outfile))
                continue

            bnch = res_dict[infile]

            if bnch.path is None or not os.path.isfile(bnch.path):
                self._write_mosaic(f_pfx, outfile)
            else:
                shutil.copyfile(bnch.path, outfile)
                self._write_mef(f_pfx, bnch.extlist, outfile)

            self.logger.info('{0} written'.format(outfile))

        self.w.status.set_text('Saving done, see log')
714171
def clean_videos(self):
        
        if self.videos:
            self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)]
403488
def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
        """"""
        from matplotlib import animation
        anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
        FFMpegWriter = animation.writers['ffmpeg']
        writer = FFMpegWriter(bitrate= bitrate, fps=fps)
        # Save #
        self.avi_path = self.base_dir + self.short_name + '.avi'
        anim.save(self.avi_path, writer=writer, codec='x264')
834060
def _load_video(video_filename):
    """"""
    video_filename = str(video_filename)
    print("Loading " + video_filename)
    if not os.path.isfile(video_filename):
        raise Exception("File Not Found: %s" % video_filename)
    # noinspection PyArgumentList
    capture = cv2.VideoCapture(video_filename)
    frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    width, height = get_capture_dimensions(capture)
    fps = int(capture.get(cv2.CAP_PROP_FPS))
    x = 0
    vid_frames = numpy.zeros((frame_count, height, width, 3), dtype='uint8')
    while capture.isOpened():
        ret, frame = capture.read()
        if not ret:
            break

        vid_frames[x] = frame
        x += 1
    capture.release()

    return vid_frames, fps
494819
def save(self, *args, **kwargs):
        """"""

        if not self.image:

            # Fetch image
            url = "http://img.youtube.com/vi/%s/0.jpg" % self.youtube_id
            response = None
            try:
                response = requests.get(url)
            except requests.exceptions.RequestException:
                # Nothing we can really do in this case
                pass

            if response is not None:
                # Jump through filesystem hoop to please photologue
                filename = self.youtube_id + '.jpg'
                filepath = os.path.join(mkdtemp(), filename)
                fp = open(filepath, 'wb')
                try:
                    fp.write(response.content)
                finally:
                    fp.close()

                # Check for a valid image
                image = None
                try:
                    image = Image.open(filepath)
                except IOError:
                    os.remove(filepath)

                if image is not None:
                    try:
                        # Overlay a play button if possible
                        video_play_image = \
                            preferences.GalleryPreferences.video_play_image
                        if video_play_image:
                            overlay = Image.open(video_play_image)
                            # Downsize image_overlay if it is larger than image
                            w1, h1 = image.size
                            w2, h2 = overlay.size
                            if w2 > w1 or h2 > h1:
                                ratio1 = w1 / float(h1)
                                ratio2 = w2 / float(h2)
                                if ratio1 > ratio2:
                                    resize_fract = h1 / float(h2)
                                else:
                                    resize_fract = w1 / float(w2)

                                overlay.resize(
                                    w2 * resize_fract,
                                    h2 * resize_fract,
                                    Image.ANTIALIAS
                                )

                            image.paste(
                                overlay,
                                (int((w1 - w2) / 2.0), int((h1 - h2) / 2.0)),
                                mask=overlay
                            )
                            image.save(filepath)

                        # Finally set image
                        image = File(open(filepath, 'rb'))
                        image.name = filename
                        self.image = image
                    finally:
                        os.remove(filepath)

        super(VideoEmbed, self).save(*args, **kwargs)
833263
def save_media(self):
        """"""
        chunk_path = fileops.get_chunk_path_from_string(
            self.model.unique_field
        )

        for i, mediafile in enumerate(self.model.media_list):
            filename = os.path.join(
                self._get_prefix(),
                chunk_path,
                "%s_%d" % (self.model.unique_field, i)
            )
            self.store.store_media(filename, mediafile)
1282014
def save_as(self, filename):
        
        with open(filename, 'w+b') as f:
            for chunk in self._download():
                f.write(chunk)
712683
def _save_files(self, data, dtype_out_time):
        """"""
        path = self.path_out[dtype_out_time]
        if not os.path.isdir(self.dir_out):
            os.makedirs(self.dir_out)
        if 'reg' in dtype_out_time:
            try:
                reg_data = xr.open_dataset(path)
            except (EOFError, RuntimeError, IOError):
                reg_data = xr.Dataset()
            reg_data.update(data)
            data_out = reg_data
        else:
            data_out = data
        if isinstance(data_out, xr.DataArray):
            data_out = xr.Dataset({self.name: data_out})
        data_out.to_netcdf(path, engine='netcdf4', format='NETCDF3_64BIT')
1157405
def save(self):
        
        from settings import PROCESSORS
        from .filesystem import makedirs

        if self.im is None:
            # If we got here something very strange is going on that I can't even
            # predict.
            return  # pragma: no cover
        makedirs(self.output_path)
        for action, arg in self.actions:
            action = PROCESSORS[action]
            if self.frames:
                new_frames = []
                for frame in self.frames:
                    new_frames.append(action.process(frame, arg))
                self.frames = new_frames
            else:
                self.im = action.process(self.im, arg)

        self.im = optimize.optimize(self.im, fmt=self.format, quality=self.quality)

        kwargs = {
            'format': self.format,
            'optimize': True,
            'quality': self.quality,
        }
        if self.format == 'jpeg':
            kwargs['progressive'] = True

        if self.filename.startswith('s3://'):
            import cStringIO
            from filesystem import s3
            output = cStringIO.StringIO()
            if self.frames:
                images2gif.write_gif(output, self.frames)
            else:
                self.im.save(output, **kwargs)
            output.reset()
            s3.put_file(output, self.filename)
        else:
            if self.frames:
                images2gif.write_gif(self.filename, self.frames)
            else:
                self.im.save(self.filename, **kwargs)
800382
public function saveFiles()
    {
        $fileFields = $this->getFileFields();

        foreach ($fileFields as $fieldName => $options) {
            $file = Request::file($fieldName);
            if ($file instanceof UploadedFile && $file->isValid()) {
                $filename = $file->getClientOriginalName();
                $fileSavePath = $this->getFileSavePath($options['dirName']);

                $file->move($fileSavePath, $filename);

                $this->attributes[$fieldName] = $fileSavePath.$filename;
            }
        }
    }
1367598
function(options) {
            options = paper.Base.set({
                fps: 30,
                prefix: 'frame-',
                amount: 1,
            }, options);
            if (!options.directory)
                throw new Error('Missing options.directory');
            var view = this,
                count = 0,
                frameDuration = 1 / options.fps,
                startTime = Date.now(),
                lastTime = startTime,
                padding = options.padding || ((options.amount - 1) + '').length,
                paddedStr = Array(padding + 1).join('0');

            // Start exporting frames by exporting the first frame:
            exportFrame(options);

            function exportFrame() {
                // Convert to a Base object, for #toString()
                view.emit('frame', new paper.Base({
                    delta: frameDuration,
                    time: frameDuration * count,
                    count: count
                }));
                var file = path.join(options.directory, options.prefix +
                        (paddedStr + count).slice(-padding) + '.png');
                var out = view.exportImage(file, function() {
                    // Once the file has been closed, export the next fame:
                    var then = Date.now();
                    if (options.onProgress) {
                        options.onProgress({
                            count: count,
                            amount: options.amount,
                            percentage: Math.round((count + 1) / options.amount
                                    * 10000) / 100,
                            time: then - startTime,
                            delta: then - lastTime
                        });
                    }
                    lastTime = then;
                    if (++count < options.amount) {
                        exportFrame();
                    } else {
                        // Call onComplete handler when finished:
                        if (options.onComplete) {
                            options.onComplete();
                        }
                    }
                });
            }
        }
481139
def record_to_fs(self):
        """"""

        fr = self.record

        fn_path = self.file_name

        if fr.contents:
            if six.PY2:
                with self._fs.open(fn_path, 'wb') as f:
                    self.record_to_fh(f)
            else:
                # py3
                with self._fs.open(fn_path, 'w', newline='') as f:
                    self.record_to_fh(f)