Downloads one image, crops it, resizes it and saves it locally.
506835
def download_image(image_id, url, x1, y1, x2, y2, output_dir):
  """"""
  output_filename = os.path.join(output_dir, image_id + '.png')
  if os.path.exists(output_filename):
    # Don't download image if it's already there
    return True
  try:
    # Download image
    url_file = urlopen(url)
    if url_file.getcode() != 200:
      return False
    image_buffer = url_file.read()
    # Crop, resize and save image
    image = Image.open(BytesIO(image_buffer)).convert('RGB')
    w = image.size[0]
    h = image.size[1]
    image = image.crop((int(x1 * w), int(y1 * h), int(x2 * w),
                        int(y2 * h)))
    image = image.resize((299, 299), resample=Image.ANTIALIAS)
    image.save(output_filename)
  except IOError:
    return False
  return True
1039323
def generateThumbnail(self):
        """"""
        source = ROOT / self.source.name
        thumbnail = source.parent / '_{}.jpg'.format(source.namebase)

        # -- Save thumbnail and put into queue
        poster = source.parent / '__{}.jpg'.format(source.namebase)
        cmd = [FROG_FFMPEG, '-i', str(source), '-ss', '1', '-vframes', '1', str(thumbnail), '-y']
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        proc.communicate()
        image = pilImage.open(thumbnail)
        image.save(poster)
        self.poster = poster.replace(ROOT, '')

        box, width, height = cropBox(self.width, self.height)

        # Resize
        image.thumbnail((width, height), pilImage.ANTIALIAS)
        # Crop from center
        box = cropBox(*image.size)[0]
        image = image.crop(box)
        # save
        self.thumbnail = thumbnail.replace(ROOT, '')
        image.save(thumbnail)
13526
def generateThumbnail(self):
        """"""
        image = pilImage.open(ROOT / self.source.name)
        box, width, height = cropBox(self.width, self.height)

        # Resize
        image.thumbnail((width, height), pilImage.ANTIALIAS)
        # Crop from center
        box = cropBox(*image.size)[0]
        image = image.crop(box)
        # save
        self.thumbnail = self.source.name.replace(self.hash, '__{}'.format(self.hash))
        image.save(ROOT / self.thumbnail.name)
1129461
def store_image(self, http_client, link_hash, src, config):
        
        # check for a cache hit already on disk
        image = self.read_localfile(link_hash, src, config)
        if image:
            return image

        # no cache found download the image
        data = self.fetch(http_client, src)
        if data:
            image = self.write_localfile(data, link_hash, src, config)
            if image:
                return image

        return None
215129
function downloadImage(map) {
    map.exportAsImage(function (url) {
        let a = document.createElement("a");
        a.download = "example";
        a.href = url;
        a.click();
    }, "jpeg");
}
894549
def _download_images(data, img_cols):
  """"""

  images = collections.defaultdict(list)
  for d in data:
    for img_col in img_cols:
      if d.get(img_col, None):
        if isinstance(d[img_col], Image.Image):
          # If it is already an Image, just copy and continue.
          images[img_col].append(d[img_col])
        else:
          # Otherwise it is image url. Load the image.
          with file_io.FileIO(d[img_col], 'rb') as fi:
            im = Image.open(fi)
          images[img_col].append(im)
      else:
        images[img_col].append('')

  return images
948261
def apply(self, resource):
        
        if not isinstance(resource, Image.Image):
            raise ValueError('Unknown resource format')

        original_width, original_height = resource.size

        resource_format = resource.format

        if self.mode == 'outbound':
            target_width, target_height = self.outbound_sizes(original_width, original_height, self.width, self.height)
            resource = resource.resize((target_width, target_height), Image.ANTIALIAS)

            crop_sizes = self.crop_sizes(target_width, target_height, self.width, self.height)
            resource = resource.crop(crop_sizes)
        else:
            target_width, target_height = self.inset_sizes(original_width, original_height, self.width, self.height)
            resource = resource.resize((target_width, target_height), Image.ANTIALIAS)

        resource.format = resource_format

        return resource
11541
def make_thumbnail(file, size, bbox=None):
    '''
    
    '''
    image = Image.open(file)
    if bbox:
        thumbnail = crop_thumbnail(image, size, bbox)
    else:
        thumbnail = center_thumbnail(image, size)
    return _img_to_file(thumbnail)
844302
def download(client, target_dir):
    """"""
    print('download image previews')
    print(
        "Warning! Downloaded images are only previews!"
        "They may be to small for upload.")
    tree = {}
    listings = client.list('listings')
    languages = map(lambda listing: listing['language'], listings)

    parameters = [{'imageType': image_type, 'language': language}
                  for image_type in image_types for language in languages]
    tree = {image_type: {language: list()
                         for language in languages}
            for image_type in image_types}

    for params in parameters:
        result = client.list('images', **params)
        image_type = params['imageType']
        language = params['language']
        tree[image_type][language] = map(
            lambda r: r['url'], result)

    for image_type, language_map in tree.items():
        for language, files in language_map.items():
            if len(files) > 0:
                mkdir_p(
                    os.path.join(target_dir, 'images', image_type, language))
            if image_type in single_image_types:
                if len(files) > 0:
                    image_url = files[0]
                    path = os.path.join(
                        target_dir,
                        'images',
                        image_type,
                        language,
                        image_type)
                    load_and_save_image(image_url, path)
            else:
                for idx, image_url in enumerate(files):
                    path = os.path.join(
                        target_dir,
                        'images',
                        image_type,
                        language,
                        image_type + '_' + str(idx))
                    load_and_save_image(image_url, path)
1082775
def _save_image(fig, filename, filetype='png', resolution=300):
    
    if filename:
        filename, filetype, resolution = build_filename(filename,
                                                        filetype,
                                                        resolution)
        fig.savefig(filename, dpi=resolution, format=filetype)
    else:
        pass
227268
def save(self, fn:PathOrStr):
        ""
        x = image2np(self.data*255).astype(np.uint8)
        PIL.Image.fromarray(x).save(fn)
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')
510919
def fixed_crop(src, x0, y0, w, h, size=None, interpolation=cv2.INTER_CUBIC):
    """"""
    out = mx.nd.crop(src, begin=(y0, x0, 0), end=(y0+h, x0+w, int(src.shape[2])))
    if size is not None and (w, h) != size:
        out = resize(out, size, interpolation=interpolation)
    return out
416237
public static void save(Bitmap src, String fileName) throws ImageSaveException {
        saveJpeg(src, fileName, JPEG_QUALITY);
    }
87183
def resize(image, width=None, height=None, crop=False, namespace="resized"):
    
    return resize_lazy(image=image, width=width, height=height, crop=crop,
                       namespace=namespace, as_url=True)
1112588
public function performCrop()
    {
        $req_post = esc_html( $_POST['post'] );
        if (!current_user_can('edit_post', $req_post))
            json_response([
                'status'=>'error',
                'message'=>'You are not strong enough, smart enough or fast enough.'
                          ]);


        $size = esc_html($_POST['size']);
        $crop_width = esc_html($_POST['width']);
        $crop_height = esc_html($_POST['height']);
        $crop_x = esc_html($_POST['x']);
        $crop_y = esc_html($_POST['y']);

        $img_path = _load_image_to_edit_path( $req_post );
        $meta = wp_get_attachment_metadata( $req_post );
        $img_editor = wp_get_image_editor( $img_path );
        if (is_wp_error($img_editor))
            json_response([
                              'status'=>'error',
                              'message'=>'Could not create image editor.'
                          ]);

        $crop_size=ilab_get_image_sizes($size);
        $dest_width = $crop_size['width'];
        $dest_height = $crop_size['height'];

        $img_editor->crop($crop_x, $crop_y, $crop_width, $crop_height, $dest_width, $dest_height, false );
        $img_editor->set_quality($this->cropQuality);
        $save_path_parts = pathinfo($img_path);

        $path_url=parse_url($img_path);
        if (($path_url!==false) && (isset($path_url['scheme'])))
        {
            $parsed_path=pathinfo($path_url['path']);
            $img_subpath=apply_filters('ilab_s3_process_file_name',$parsed_path['dirname']);

            $upload_dir=wp_upload_dir();
            $save_path=$upload_dir['basedir'].$img_subpath;
            @mkdir($save_path,0777,true);
        }
        else
            $save_path=$save_path_parts['dirname'];

        $extension=$save_path_parts['extension'];
        $filename=preg_replace('#^(IL[0-9-]*)#','',$save_path_parts['filename']);
        $filename='IL'.date("YmdHis").'-'.$filename.'-'.$dest_width.'x'.$dest_height.'.'.$extension;

        if (isset($meta['sizes'][$size]))
        {
            $meta['sizes'][$size]['file']=$filename;
            $meta['sizes'][$size]['width']=$dest_width;
            $meta['sizes'][$size]['height']=$dest_height;
            $meta['sizes'][$size]['crop']=[
                'x'=>round($crop_x),
                'y'=>round($crop_y),
                'w'=>round($crop_width),
                'h'=>round($crop_height)
            ];
        }
        else
        {
            $meta['sizes'][$size] = array(
                'file' => $filename,
                'width' => $dest_width,
                'height' => $dest_height,
                'mime-type' => $meta['sizes']['thumbnail']['mime-type'],
                'crop'=> [
                    'x'=>round($crop_x),
                    'y'=>round($crop_y),
                    'w'=>round($crop_width),
                    'h'=>round($crop_height)
                ]
            );
        }

        $img_editor->save($save_path . '/' . $filename);

        // Let S3 upload the new crop
        $processedSize = apply_filters('ilab_s3_process_crop', $size, $save_path, $filename, $meta['sizes'][$size]);
        if ($processedSize)
            $meta['sizes'][$size] = $processedSize;

        wp_update_attachment_metadata($req_post, $meta);

        $attrs = wp_get_attachment_image_src($req_post, $size);
        list($full_src,$full_width,$full_height,$full_cropped)=$attrs;

        json_response([
            'status'=>'ok',
            'src'=>$full_src,
            'width'=>$full_width,
            'height'=>$full_height
        ]);
    }
239626
def _cropbox(self, image, x, y, x2, y2):
        
        image['options']['crop'] = '%sx%s+%s+%s' % (x2 - x, y2 - y, x, y)
        image['size'] = (x2 - x, y2 - y)  # update image size
        return image