def get_image_from_uri(cache, url_fetcher, options, url, forced_mime_type=None,
                       context=None, orientation='from-image'):
    """Get an Image instance from an image URI."""
    if url in cache:
        return cache[url]

    try:
        with fetch(url_fetcher, url) as result:
            parsed_url = urlparse(result.get('redirected_url'))
            if parsed_url.scheme == 'file':
                filename = url2pathname(parsed_url.path)
            else:
                filename = None
            if 'string' in result:
                string = result['string']
            else:
                string = result['file_obj'].read()
            mime_type = forced_mime_type or result['mime_type']

        image = None
        svg_exceptions = []
        # Try to rely on given mimetype for SVG
        if mime_type == 'image/svg+xml':
            try:
                tree = ElementTree.fromstring(string)
                image = SVGImage(tree, url, url_fetcher, context)
            except Exception as svg_exception:
                svg_exceptions.append(svg_exception)
        # Try pillow for raster images, or for failing SVG
        if image is None:
            try:
                pillow_image = Image.open(BytesIO(string))
            except Exception as raster_exception:
                if mime_type == 'image/svg+xml':
                    # Tried SVGImage then Pillow for a SVG, abort
                    raise ImageLoadingError.from_exception(svg_exceptions[0])
                try:
                    # Last chance, try SVG
                    tree = ElementTree.fromstring(string)
                    image = SVGImage(tree, url, url_fetcher, context)
                except Exception:
                    # Tried Pillow then SVGImage for a raster, abort
                    raise ImageLoadingError.from_exception(raster_exception)
            else:
                # Store image id to enable cache in Stream.add_image
                image_id = md5(url.encode(), usedforsecurity=False).hexdigest()
                image = RasterImage(
                    pillow_image, image_id, string, filename, cache,
                    orientation, options)

    except (URLFetchingError, ImageLoadingError) as exception:
        LOGGER.error('Failed to load image at %r: %s', url, exception)
        LOGGER.debug('Error while loading image:', exc_info=exception)
        image = None

    cache[url] = image
    return image
Get an Image instance from an image URI.
weasyprint/images.py