Returns thumbnail as an ImageFile instance for file with geometry and
        options given. First it will try to get it from the key value store,
        secondly it will create it.
558107
def get_thumbnail(self, file_, geometry_string, **options):
        
        logger.debug('Getting thumbnail for file [%s] at [%s]', file_, geometry_string)

        if file_:
            source = ImageFile(file_)
        else:
            raise ValueError('falsey file_ argument in get_thumbnail()')

        # preserve image filetype
        if settings.THUMBNAIL_PRESERVE_FORMAT:
            options.setdefault('format', self._get_format(source))

        for key, value in self.default_options.items():
            options.setdefault(key, value)

        # For the future I think it is better to add options only if they
        # differ from the default settings as below. This will ensure the same
        # filenames being generated for new options at default.
        for key, attr in self.extra_options:
            value = getattr(settings, attr)
            if value != getattr(default_settings, attr):
                options.setdefault(key, value)

        name = self._get_thumbnail_filename(source, geometry_string, options)
        thumbnail = ImageFile(name, default.storage)
        cached = default.kvstore.get(thumbnail)

        if cached:
            return cached

        # We have to check exists() because the Storage backend does not
        # overwrite in some implementations.
        if settings.THUMBNAIL_FORCE_OVERWRITE or not thumbnail.exists():
            try:
                source_image = default.engine.get_image(source)
            except IOError as e:
                logger.exception(e)
                if settings.THUMBNAIL_DUMMY:
                    return DummyImageFile(geometry_string)
                else:
                    # if S3Storage says file doesn't exist remotely, don't try to
                    # create it and exit early.
                    # Will return working empty image type; 404'd image
                    logger.warning(
                        'Remote file [%s] at [%s] does not exist',
                        file_, geometry_string,
                    )
                    return thumbnail

            # We might as well set the size since we have the image in memory
            image_info = default.engine.get_image_info(source_image)
            options['image_info'] = image_info
            size = default.engine.get_image_size(source_image)
            source.set_size(size)

            try:
                self._create_thumbnail(source_image, geometry_string, options,
                                       thumbnail)
                self._create_alternative_resolutions(source_image, geometry_string,
                                                     options, thumbnail.name)
            finally:
                default.engine.cleanup(source_image)

        # If the thumbnail exists we don't create it, the other option is
        # to delete and write but this could lead to race conditions so I
        # will just leave that out for now.
        default.kvstore.get_or_set(source)
        default.kvstore.set(thumbnail, source)
        return thumbnail
914373
def _thumbnail_s3(self, original_filename, thumb_filename,
                      thumb_size, thumb_url, bucket_name,
                      crop=None, bg=None, quality=85):
        """"""

        scheme = self.app.config.get('THUMBNAIL_S3_USE_HTTPS') and 'https' or 'http'

        thumb_url_full = url_for_s3(
            'static',
            bucket_name=self.app.config.get('THUMBNAIL_S3_BUCKET_NAME'),
            filename=thumb_url,
            scheme=scheme)
        original_url_full = url_for_s3(
            'static',
            bucket_name=bucket_name,
            filename=self._get_s3_path(original_filename).replace('static/', ''),
            scheme=scheme)

        # Return the thumbnail URL now if it already exists on S3.
        # HTTP HEAD request saves us actually downloading the image
        # for this check.
        # Thanks to:
        # http://stackoverflow.com/a/16778749/2066849
        try:
            resp = httplib2.Http().request(thumb_url_full, 'HEAD')
            resp_status = int(resp[0]['status'])
            assert(resp_status < 400)
            return thumb_url_full
        except Exception:
            pass

        # Thanks to:
        # http://stackoverflow.com/a/12020860/2066849
        try:
            fd = urllib.urlopen(original_url_full)
            temp_file = BytesIO(fd.read())
            image = Image.open(temp_file)
        except Exception:
            return ''

        img = self._thumbnail_resize(image, thumb_size, crop=crop, bg=bg)

        temp_file = BytesIO()
        img.save(temp_file, image.format, quality=quality)

        conn = S3Connection(self.app.config.get('THUMBNAIL_S3_ACCESS_KEY_ID'), self.app.config.get('THUMBNAIL_S3_ACCESS_KEY_SECRET'))
        bucket = conn.get_bucket(self.app.config.get('THUMBNAIL_S3_BUCKET_NAME'))

        path = self._get_s3_path(thumb_filename)
        k = bucket.new_key(path)

        try:
            k.set_contents_from_string(temp_file.getvalue())
            k.set_acl(self.app.config.get('THUMBNAIL_S3_ACL', 'public-read'))
        except S3ResponseError:
            return ''

        return thumb_url_full
843802
def get_image(self, filename: str=None) -> None:
        """"""
        if filename is None:
            filename = "{0}.png".format(self.name)

        endpoint = "/account/{0}/savings-goals/{1}/photo".format(
            self._account_uid,
            self.uid
        )

        response = get(
            _url(endpoint, self._sandbox),
            headers=self._auth_headers
        )
        response.raise_for_status()

        base64_image = response.json()['base64EncodedPhoto']
        with open(filename, 'wb') as file:
            file.write(b64decode(base64_image))
1079124
def __get_img(self):
        
        with self.fs.open(self.__img_path, 'rb') as fd:
            img = PIL.Image.open(fd)
            img.load()
            return img
490446
def _create_alternative_resolutions(self, source_image, geometry_string,
                                        options, name):
        
        ratio = default.engine.get_image_ratio(source_image, options)
        geometry = parse_geometry(geometry_string, ratio)
        file_name, dot_file_ext = os.path.splitext(name)

        for resolution in settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS:
            resolution_geometry = (int(geometry[0] * resolution), int(geometry[1] * resolution))
            resolution_options = options.copy()
            if 'crop' in options and isinstance(options['crop'], string_types):
                crop = options['crop'].split(" ")
                for i in range(len(crop)):
                    s = re.match(r"(\d+)px", crop[i])
                    if s:
                        crop[i] = "%spx" % int(int(s.group(1)) * resolution)
                resolution_options['crop'] = " ".join(crop)

            image = default.engine.create(source_image, resolution_geometry, options)
            thumbnail_name = '%(file_name)s%(suffix)s%(file_ext)s' % {
                'file_name': file_name,
                'suffix': '@%sx' % resolution,
                'file_ext': dot_file_ext
            }
            thumbnail = ImageFile(thumbnail_name, default.storage)
            default.engine.write(image, resolution_options, thumbnail)
            size = default.engine.get_image_size(image)
            thumbnail.set_size(size)
1123149
def thumbnail_url(options = {})
      return if picture.nil?

      crop = crop_values_present? || content.settings_value(:crop, options)
      size = render_size || content.settings_value(:size, options)

      options = {
        size: thumbnail_size(size, crop),
        crop: !!crop,
        crop_from: crop_from.presence,
        crop_size: crop_size.presence,
        flatten: true,
        format: picture.image_file_format
      }

      picture.url(options)
    end
51714
function getExampleThumbnails({ allFile, allImageSharp }) {
  // this function associates the path of an original image
  // with the public url of a thumbnail, resized server side by imageSharp.
  if (
    !allFile ||
    !allFile.edges ||
    !allFile.edges.length ||
    !allImageSharp ||
    !allImageSharp.edges ||
    !allImageSharp.edges.length
  ) {
    log.log({ color: COLOR.YELLOW, priority: 1 }, `No thumbnails created.`)();
    return {};
  }
  // in a first pass, we create a lookup - original path to internal gatsby node id.
  /* eslint-disable no-param-reassign */
  const idLookup = allFile.edges.reduce((lookup, { node }) => {
    lookup[node.id] = node.relativePath;
    return lookup;
  }, {});

  // in a second path, we associate each thumbnail with the path of the original
  // image, using the node id of this original image and the lookup
  // we just created.

  const pathLookup = allImageSharp.edges.reduce((lookup, { node }) => {
    const originalImageId = node.parent.id;
    const originalImagePath = idLookup[originalImageId];
    lookup[originalImagePath] = node.resize.src;
    return lookup;
  }, {});

  /* eslint-enable no-param-reassign */
  return pathLookup;
}
1117164
@WorkerThread
    @Nullable
    public String createThumbnailForImage(String imagePath) {
        if (TextUtils.isEmpty(imagePath)) return null;

        File inFile = new File(imagePath);
        if (!inFile.exists()) return null;

        File thumbnailFile = randomPath(imagePath);
        if (thumbnailFile.exists()) return thumbnailFile.getAbsolutePath();

        Bitmap inBitmap = readImageFromPath(imagePath, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
        if (inBitmap == null) return null;

        ByteArrayOutputStream compressStream = new ByteArrayOutputStream();
        inBitmap.compress(Bitmap.CompressFormat.JPEG, THUMBNAIL_QUALITY, compressStream);

        try {
            compressStream.close();
            thumbnailFile.createNewFile();

            FileOutputStream writeStream = new FileOutputStream(thumbnailFile);
            writeStream.write(compressStream.toByteArray());
            writeStream.flush();
            writeStream.close();
            return thumbnailFile.getAbsolutePath();
        } catch (Exception ignored) {
            return null;
        }
    }
899726
def generate_thumb(self, image):
        
        image_file = image.file
        picture = Image.open(image_file).convert('RGB')
        picture.thumbnail((10, 10))
        picture.filter(ImageFilter.GaussianBlur(radius=4))
        absolute_path = self.build_thumb_path(image)
        self.save_thumb(picture, absolute_path)
867388
function getImageSizeFromFile(file) {
	return new Promise((resolve, reject) => {
		const isDataUrl = file.match(/^data:.+?;base64,/);

		if (isDataUrl) {
			// NB should use sync version of `sizeOf()` for buffers
			try {
				const data = Buffer.from(file.slice(isDataUrl[0].length), 'base64');
				return resolve(sizeForFileName('', sizeOf(data)));
			} catch (err) {
				return reject(err);
			}
		}

		sizeOf(file, (err, size) => {
			if (err) {
				reject(err);
			} else {
				resolve(sizeForFileName(path.basename(file), size));
			}
		});
	});
}
1021693
def get_filestore_instance(img_dir=None, data_dir=None):
    """"""
    global _filestore_instances

    key = "%s:%s" % (img_dir, data_dir)

    try:
        instance = _filestore_instances[key]
    except KeyError:
        instance = FileStore(
            img_dir=img_dir, data_dir=data_dir
        )
        _filestore_instances[key] = instance

    return instance
997121
function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
            var promiseToReturn = new qq.Promise(),
                fileOrUrl, options;

            if (this._imageGenerator) {
                fileOrUrl = this._thumbnailUrls[fileId];
                options = {
                    customResizeFunction: customResizeFunction,
                    maxSize: maxSize > 0 ? maxSize : null,
                    scale: maxSize > 0
                };

                // If client-side preview generation is possible
                // and we are not specifically looking for the image URl returned by the server...
                if (!fromServer && qq.supportedFeatures.imagePreviews) {
                    fileOrUrl = this.getFile(fileId);
                }

                /* jshint eqeqeq:false,eqnull:true */
                if (fileOrUrl == null) {
                    promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."});
                }
                else {
                    this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(
                        function success(modifiedContainer) {
                            promiseToReturn.success(modifiedContainer);
                        },

                        function failure(container, reason) {
                            promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"});
                        }
                    );
                }
            }
            else {
                promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"});
            }

            return promiseToReturn;
        }
890419
def getImage(self):
        '''
        

        '''
        self.lock.acquire()
        image = self.data
        self.lock.release()
        
        return image
635390
def database_get_image_dimensions(file, close=False, dimensions=None):
    
    storage_hash = utils.get_storage_hash(file.storage)
    dimensions = None
    dimensions_cache = None
    try:
        thumbnail = models.Thumbnail.objects.select_related('dimensions').get(
            storage_hash=storage_hash, name=file.name)
    except models.Thumbnail.DoesNotExist:
        thumbnail = None
    else:
        try:
            dimensions_cache = thumbnail.dimensions
        except models.ThumbnailDimensions.DoesNotExist:
            dimensions_cache = None
        if dimensions_cache:
            return dimensions_cache.width, dimensions_cache.height
    dimensions = get_image_dimensions(file, close=close)
    if settings.THUMBNAIL_CACHE_DIMENSIONS and thumbnail:
        # Using get_or_create in case dimensions were created
        # while running get_image_dimensions.
        models.ThumbnailDimensions.objects.get_or_create(
            thumbnail=thumbnail,
            defaults={'width': dimensions[0], 'height': dimensions[1]})
    return dimensions
755954
function () {
		var Class = this.constructor,
			x, y,
			width = this.getWidth(),
			height = this.getHeight(),
			image = Class.createImage(height, width);

		for (x = 0; x < width; x++) {
			for (y = 0; y < height; y++) {
				image.setPixel(y, width - x - 1, this.getPixel(x, y));
			}
		}

		return image;
	}
489522
def get_thumbnails(self, *args, **kwargs):
        
        # First, delete any related thumbnails.
        source_cache = self.get_source_cache()
        if source_cache:
            thumbnail_storage_hash = utils.get_storage_hash(
                self.thumbnail_storage)
            for thumbnail_cache in source_cache.thumbnails.all():
                # Only iterate files which are stored using the current
                # thumbnail storage.
                if thumbnail_cache.storage_hash == thumbnail_storage_hash:
                    yield ThumbnailFile(name=thumbnail_cache.name,
                                        storage=self.thumbnail_storage)
1110176
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False):
        
        thumbnail_options = self.get_options(thumbnail_options)
        names = [
            self.get_thumbnail_name(
                thumbnail_options, transparent=False,
                high_resolution=high_resolution)]
        transparent_name = self.get_thumbnail_name(
            thumbnail_options, transparent=True,
            high_resolution=high_resolution)
        if transparent_name not in names:
            names.append(transparent_name)

        for filename in names:
            exists = self.thumbnail_exists(filename)
            if exists:
                thumbnail_file = ThumbnailFile(
                    name=filename, storage=self.thumbnail_storage,
                    thumbnail_options=thumbnail_options)
                if settings.THUMBNAIL_CACHE_DIMENSIONS:
                    # If this wasn't local storage, exists will be a thumbnail
                    # instance so we can store the image dimensions now to save
                    # a future potential query.
                    thumbnail_file.set_image_dimensions(exists)
                return thumbnail_file