Create enhanced image frames to save to a file.
353540
def _get_animation_frames(self, all_datasets, shape, fill_value=None,
                              ignore_missing=False):
        """"""
        for idx, ds in enumerate(all_datasets):
            if ds is None and ignore_missing:
                continue
            elif ds is None:
                log.debug("Missing frame: %d", idx)
                data = da.zeros(shape, dtype=np.uint8, chunks=shape)
                data = xr.DataArray(data)
            else:
                img = get_enhanced_image(ds)
                data, mode = img.finalize(fill_value=fill_value)
                if data.ndim == 3:
                    # assume all other shapes are (y, x)
                    # we need arrays grouped by pixel so
                    # transpose if needed
                    data = data.transpose('y', 'x', 'bands')
            yield data.data
216595
def write_image(filename, image):
    
    data_format = get_data_format(filename)
    if data_format is MimeType.JPG:
        LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.')
    return Image.fromarray(image).save(filename)
60365
def render_to_file(self, filename, **kwargs):
        """"""
        with io.open(filename, 'w', encoding='utf-8') as f:
            f.write(self.render(is_unicode=True, **kwargs))
1367658
def write(self, filename=None):
        """"""
        if filename is None:
            filename = self._filename

        exif_bytes = piexif.dump(self._ef)

        with open(self._filename, "rb") as fin:
            img = fin.read()
        try:
            piexif.insert(exif_bytes, img, filename)

        except IOError:
            type, value, traceback = sys.exc_info()
            print >> sys.stderr, "Error saving file:", value
1165590
def savefig(viz, name, gallery=GALLERY):
    
    if not path.exists(gallery):
        os.makedirs(gallery)

    # Must save as png
    if len(name.split(".")) > 1:
        raise ValueError("name should not specify extension")

    outpath = path.join(gallery, name+".png")
    viz.poof(outpath=outpath)
    print("created {}".format(outpath))
869122
def create_image(self, image_file, caption):
        
        suffix = 'png'
        if image_file:
            img = Image.open(os.path.join(self.gallery, image_file))
            width, height = img.size
            ratio = width/WIDTH
            img = img.resize((int(width // ratio),
                              int(height // ratio)),
                             Image.ANTIALIAS)
        else:
            img = Image.new('RGB', (WIDTH, HEIGHT), 'black')
            image = self.add_caption(img, caption)
            
        image = img

        return image
108264
def _save_file(self, filename, contents):
        """"""
        with open(filename, 'w') as f:
            f.write(contents)
686885
def save(self, *args, **kwargs):
        """"""

        super(MP4, self).save(*args, **kwargs)
352749
private static void save(Bitmap src, String fileName, Bitmap.CompressFormat format, int quality) throws ImageSaveException {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(fileName);
            src.compress(format, quality, outputStream);
            outputStream.close();
        } catch (IOException e) {
            throw new ImageSaveException(e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
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)
1337969
def _pack_image(filename, max_size, form_field='image', f=None):
        """"""
        # image must be less than 700kb in size
        if f is None:
            try:
                if os.path.getsize(filename) > (max_size * 1024):
                    raise TweepError('File is too big, must be less than %skb.' % max_size)
            except os.error as e:
                raise TweepError('Unable to access file: %s' % e.strerror)

            # build the mulitpart-formdata body
            fp = open(filename, 'rb')
        else:
            f.seek(0, 2)  # Seek to end of file
            if f.tell() > (max_size * 1024):
                raise TweepError('File is too big, must be less than %skb.' % max_size)
            f.seek(0)  # Reset to beginning of file
            fp = f

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise TweepError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

        if isinstance(filename, six.text_type):
            filename = filename.encode('utf-8')

        BOUNDARY = b'Tw3ePy'
        body = []
        body.append(b'--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="{0}";'
                    ' filename="{1}"'.format(form_field, filename)
                    .encode('utf-8'))
        body.append('Content-Type: {0}'.format(file_type).encode('utf-8'))
        body.append(b'')
        body.append(fp.read())
        body.append(b'--' + BOUNDARY + b'--')
        body.append(b'')
        fp.close()
        body = b'\r\n'.join(body)

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': str(len(body))
        }

        return headers, body
621392
def store_media(self, filename, mediafile):
        """"""
        filename = os.path.join(
            self.img_dir,
            filename
        )
        fileops.create_dirs(
            os.path.dirname(filename)
        )
        mediafile.fetch_to_file(filename)
1164347
def save(self, filename):
        
        with open(filename, "wb") as fd:
            fd.write(self.__buff)
42679
def make_rendition(self, width, height):
        '''
        '''
        image = Image.open(self.master)
        format = image.format

        target_w = float(width)
        target_h = float(height)

        if (target_w == 0):
            target_w = self.master_width

        if (target_h == 0):
            target_h = self.master_height

        rendition_key = '%dx%d' % (target_w, target_h)

        if rendition_key in self.renditions:
            return self.renditions[rendition_key]

        if (target_w != self.master_width or target_h != self.master_height):
            r = target_w / target_h
            R = float(self.master_width) / self.master_height
            if r != R:
                if r > R:
                    crop_w = self.master_width
                    crop_h = crop_w / r
                    x = 0
                    y = int(self.master_height - crop_h) >> 1
                else:
                    crop_h = self.master_height
                    crop_w = crop_h * r
                    x = int(self.master_width - crop_w) >> 1
                    y = 0
                image = image.crop((x, y, int(crop_w + x), int(crop_h + y)))

            image.thumbnail((int(target_w), int(target_h)), Image.ANTIALIAS)

            filename, ext = os.path.splitext(self.get_master_filename())
            rendition_name = '%s/%s_%s%s' % (
                IMAGE_DIRECTORY,
                filename,
                rendition_key,
                ext
            )
            fd = BytesIO()
            image.save(fd, format)
            default_storage.save(rendition_name, fd)

            self.renditions[rendition_key] = rendition_name
            self.save()

            return rendition_name

        return self.master.name
491399
def _make_sprite_image(images, save_path):
    """"""
    if isinstance(images, np.ndarray):
        images = nd.array(images, dtype=images.dtype, ctx=current_context())
    elif not isinstance(images, (NDArray, np.ndarray)):
        raise TypeError('images must be an MXNet NDArray or numpy.ndarray,'
                        ' while received type {}'.format(str(type(images))))

    assert isinstance(images, NDArray)
    shape = images.shape
    nrow = int(np.ceil(np.sqrt(shape[0])))
    _save_image(
        images, os.path.join(save_path, 'sprite.png'), nrow=nrow, padding=0, square_image=True)
715984
def save(self, create_multiple_renditions=True,
        preserve_source_rendition=True,
        encode_to=enums.EncodeToEnum.FLV):
        
        if is_ftp_connection(self.connection) and len(self.assets) > 0:
            self.connection.post(xml=self.to_xml(), assets=self.assets)
        elif not self.id and self._filename:
            self.id = self.connection.post('create_video', self._filename,
                create_multiple_renditions=create_multiple_renditions,
                preserve_source_rendition=preserve_source_rendition,
                encode_to=encode_to,
                video=self._to_dict())
        elif not self.id and len(self.renditions) > 0:
            self.id = self.connection.post('create_video',
                video=self._to_dict())
        elif self.id:
            data = self.connection.post('update_video', video=self._to_dict())
            if data:
                self._load(data)
765262
def pack_image(filename, max_size, form_field='image'):
        """"""
        try:
            if os.path.getsize(filename) > (max_size * 1024):
                raise IdeaScalyError('File is too big, must be less than %skb.' % max_size)
        except os.error as e:
            raise IdeaScalyError('Unable to access file: %s' % e.strerror)

        # build the mulitpart-formdata body
        fp = open(filename, 'rb')

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise IdeaScalyError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise IdeaScalyError('Invalid file type for image: %s' % file_type)

        if isinstance(filename, six.text_type):
            filename = filename.encode('utf-8')

        BOUNDARY = b'Id34Sc4ly'
        body = list()
        body.append(b'--' + BOUNDARY)
        body.append('content-disposition: form-data; name="{0}";'
                    ' filename="{1}"'.format(form_field, filename)
                    .encode('utf-8'))
        body.append('content-type: {0}'.format(file_type).encode('utf-8'))
        body.append(b'')
        body.append(fp.read())
        body.append(b'--' + BOUNDARY + b'--')
        body.append(b'')
        fp.close()
        body = b'\r\n'.join(body)
        body_length = str(len(body))

        # build headers
        headers = {
            'content-type': 'multipart/form-data; boundary={0}'.format(BOUNDARY),
            'content-length': body_length
        }

        return headers, body