Find an image and download it.
336828
def run(config, clear_opt=False):
    """"""
    flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'),
                                 config.get('walls', 'api_secret'))
    width = config.getint('walls', 'width')
    height = config.getint('walls', 'height')

    # Clear out the destination dir
    if clear_opt:
        clear_dir(os.path.expanduser(config.get('walls', 'image_dir')))

    # Find an image
    tags = config.get('walls', 'tags')
    for photo in flickr.walk(tags=tags, format='etree'):
        try:
            photo_url = smallest_url(flickr, photo.get('id'), width, height)
            if photo_url:
                break
        except (KeyError, ValueError, TypeError):
            stderr_and_exit('Unexpected data from Flickr.\n')
    else:
        stderr_and_exit('No matching photos found.\n')

    # Download the image
    dest = os.path.expanduser(config.get('walls', 'image_dir'))
    try:
        download(photo_url, dest)
    except IOError:
        stderr_and_exit('Error downloading image.\n')
327325
def has_image(self, digest, mime_type, index, size=500):
        """"""
        cache_key = f"img:{index}:{size}:{digest}"
        return mime_type.startswith("image/") or cache_key in self.cache
77727
public BufferedImage downloadImage() throws Exception {
		BufferedImage image = null;
		// try to recognize the type of the image from the url so that the correct format and file extension
		// are used when saving the thumbnail image or the original image.
		// In case that the url does not contain a known image extension, the jpg extension is used.
		String[] splitted = imageUrl.split("\\.");
		String fileExtension = (splitted[splitted.length - 1]).toLowerCase();
		if (!fileExtension.equals("jpg") && !fileExtension.equals("jpeg") && !fileExtension.equals("png")
				&& !fileExtension.equals("bmp") && !fileExtension.equals("gif")) {
			fileExtension = "jpg";
		}
		// this name filename will be used for the saved image file
		String imageFilename = downloadFolder + imageId + "." + fileExtension;

		// initialize the url, checking that it is valid
		URL url = null;
		try {
			url = new URL(imageUrl);
		} catch (MalformedURLException e) {
			System.out.println("Malformed url exception. Url: " + imageUrl);
			throw e;
		}

		HttpURLConnection conn = null;
		FileOutputStream fos = null;
		ReadableByteChannel rbc = null;
		InputStream in = null;
		boolean success = false;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setInstanceFollowRedirects(followRedirects);
			conn.setConnectTimeout(connectionTimeout); // TO DO: add retries when connections times out
			conn.setReadTimeout(readTimeout);
			conn.connect();
			success = true;
		} catch (Exception e) {
			System.out.println("Connection related exception at url: " + imageUrl);
			throw e;
		} finally {
			if (!success) {
				conn.disconnect();
			}
		}

		success = false;
		try {
			in = conn.getInputStream();
			success = true;
		} catch (Exception e) {
			System.out.println("Exception when getting the input stream from the connection at url: "
					+ imageUrl);
			throw e;
		} finally {
			if (!success) {
				in.close();
			}
		}

		rbc = Channels.newChannel(in);

		// if an Exception is thrown in the following code, the file that was created must be deleted
		try {
			// just copy the file
			fos = new FileOutputStream(imageFilename);
			fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
			fos.close();
			in.close();
			rbc.close();
			conn.disconnect();
			try { // first try reading with the default class
				image = ImageIO.read(new File(imageFilename));
			} catch (IllegalArgumentException e) {
				// this exception is probably thrown because of a greyscale jpeg image
				System.out.println("Exception: " + e.getMessage() + " | Image: " + imageFilename + " URL: "
						+ imageUrl);
				image = ImageIOGreyScale.read(new File(imageFilename)); // retry with the modified class
			}
		} catch (Exception e) { // in case of any other exception delete the image and re-throw the exception
			System.out.println("Exception: " + e.toString() + " | Image: " + imageFilename + " URL: "
					+ imageUrl);
			throw (e);
		} finally {
			if (image == null) { // if the image could not be read into a BufferedImage object then delete it
				File imageFile = new File(imageFilename);
				imageFile.delete();
				System.out.println("Deleting image with id " + imageId + ", url: " + imageUrl);
				throw new Exception("Could not read into BufferedImage");
			} else {
				if (saveThumb) { // save a thumbnail of the original image
					ImageScaling scale = new ImageScaling(thumbnailSizeInPixels);
					BufferedImage scaledImage = scale.maxPixelsScaling(image);
					FileOutputStream out = new FileOutputStream(new File(imageFilename.replace("."
							+ fileExtension, "-thumb." + fileExtension)));
					ImageIO.write(scaledImage, fileExtension, out);
					out.close();
				}
				if (!saveOriginal) {// delete the original image if needed
					File imageFile = new File(imageFilename);
					imageFile.delete();
				}
			}
			// close the open streams
			fos.close();
			in.close();
			rbc.close();
			conn.disconnect();
		}
		return image;
	}
520053
def download_images(query, path, size=1024):
    '''
    
    '''
    im_size = "thumb-{0}.jpg".format(size)
    im_list = []

    for im in query:
        # Use key to create url to download from and filename to save into
        key = im['properties']['key']
        url = MAPILLARY_API_IM_RETRIEVE_URL + key + '/' + im_size
        filename = key + ".jpg"

        try:
            # Get image and save to disk
            image = urllib.URLopener()
            image.retrieve(url, path + filename)

            # Log filename and GPS location
            coords = ",".join(map(str, im['geometry']['coordinates']))
            im_list.append([filename, coords])

            print("Successfully downloaded: {0}".format(filename))
        except KeyboardInterrupt:
            break
        except Exception as e:
            print("Failed to download: {} due to {}".format(filename, e))

    return im_list
488394
function(next) {
    var self = this;
    var obj                   = {};
    obj.path                  = path.join(os.tmpdir,  randomstring.generate());
    obj.original_name         = self.document[self.has_attached_file].original_url.split('/').pop();

    this.downloadUrl(self.document[self.has_attached_file].original_url, obj.path, function() {
      self.identify({input: obj.path}, function(err, identity) {
        fs.stat(obj.path, function(err, stats) {
          obj.file_size       = stats.size;
          obj.content_type    = 'image/'+identity.format.toLowerCase();
          next(err, obj);
        })      
      })
    });
  }
1364068
def _get_image_or_404(identifier, load_image=False):
    
    try:
        image_id = int(identifier)
    except ValueError:
        raise Http404()

    ik_image = get_object_or_404(ICEkitImage, id=image_id)
    if not load_image:
        return ik_image, None

    ####################################################################
    # Image-loading incantation cribbed from easythumbnail's `pil_image`
    image = Image.open(BytesIO(ik_image.image.read()))
    # Fully load the image now to catch any problems with the image contents.
    try:
        # An "Image file truncated" exception can occur for some images that
        # are still mostly valid -- we'll swallow the exception.
        image.load()
    except IOError:
        pass
    # Try a second time to catch any other potential exceptions.
    image.load()
    if True:  # Support EXIF orientation data
        image = et_utils.exif_orientation(image)
    ####################################################################

    return ik_image, image
540287
def get(img, cache_dir=CACHE_DIR, iterative=False):
    """"""
    if os.path.isfile(img):
        wal_img = img

    elif os.path.isdir(img):
        if iterative:
            wal_img = get_next_image(img)

        else:
            wal_img = get_random_image(img)

    else:
        logging.error("No valid image file found.")
        sys.exit(1)

    wal_img = os.path.abspath(wal_img)

    # Cache the image file path.
    util.save_file(wal_img, os.path.join(cache_dir, "wal"))

    logging.info("Using image \033[1;37m%s\033[0m.", os.path.basename(wal_img))
    return wal_img
1317384
def get_image(self, source):
        
        buf = StringIO(source.read())
        return Image.open(buf)
176764
def _get_vqa_v2_image_raw_dataset(directory, image_root_url, image_urls):
  """"""
  for url in image_urls:
    filename = os.path.basename(url)
    download_url = os.path.join(image_root_url, url)
    path = generator_utils.maybe_download(directory, filename, download_url)
    unzip_dir = os.path.join(directory, filename.strip(".zip"))
    if not tf.gfile.Exists(unzip_dir):
      zipfile.ZipFile(path, "r").extractall(directory)
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)
463841
def get_image(self, img, is_train):
        """"""
        img_arr = mx.image.imread(img)
        img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
        return img_arr
483297
def download_image(self, handle, dest):
        
        shutil.copyfile(self._prefixed(handle), dest)
1183602
def get_image(verbose=False):
  """"""
  base_data = tf.constant(image_data(verbose=verbose))
  base_image = tf.image.decode_image(base_data, channels=3)
  base_image.set_shape((IMAGE_HEIGHT, IMAGE_WIDTH, 3))
  parsed_image = tf.Variable(base_image, name='image', dtype=tf.uint8)
  return parsed_image
73720
def load(cls, path):
        """"""
        assert os.path.exists(path), "No such file: %r" % path

        (folder, filename) = os.path.split(path)
        (name, extension) = os.path.splitext(filename)

        image = Image(None)
        image._path = path
        image._format = Image.image_format(extension)

        return image
1119094
def download_google_images(path:PathOrStr, search_term:str, size:str='>400*300', n_images:int=10, format:str='jpg',
                            max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList:
    
    label_path = Path(path)/search_term
    search_url = _search_url(search_term, size=size, format=format)
    if n_images <= 100: img_tuples = _fetch_img_tuples(search_url, format=format, n_images=n_images)
    else:               img_tuples = _fetch_img_tuples_webdriver(search_url, format=format, n_images=n_images)
    downloaded_images = _download_images(label_path, img_tuples, max_workers=max_workers, timeout=timeout)
    if len(downloaded_images) == 0: raise RuntimeError(f"Couldn't download any images.")
    verify_images(label_path, max_workers=max_workers)
    return get_image_files(label_path)
130205
def download_large(self, image, url_field='url'):
        
        return self.download(image, url_field=url_field, suffix='large')
1073420
def album(netease, name, id):
    """"""
    if name:
        netease.download_album_by_search(name)

    if id:
        netease.download_album_by_id(id, 'album'+str(id))