Last active
October 11, 2018 18:46
-
-
Save cedws/d72d6ff83b148dadf7be721809bcc44e to your computer and use it in GitHub Desktop.
Get the dimensions of a remote image... fast.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import aiohttp | |
# I'm importing Pillow-SIMD for increased performance, but you can use ordinary Pillow if you wish. | |
from PIL import ImageFile | |
# The remote image we'll be finding the dimensions for. | |
SOURCE = "http://rustacean.net/assets/rustacean-orig-noshadow.png" | |
async def main(): | |
# Start HTTP client. | |
async with aiohttp.ClientSession(raise_for_status=True) as session: | |
print(await get_dimensions(session, SOURCE)) | |
async def get_dimensions(session, image) -> (int, int): | |
async with session.get(image) as req: | |
parser = ImageFile.Parser() | |
# If an image can't be parsed, read 64 bytes more from the response. | |
# Will throw an exception if it reaches the end of the response body and can't parse an image. | |
# Be sure to handle this exception in production code. | |
while not parser.image: | |
parser.feed(await req.content.readexactly(64)) | |
return parser.image.size | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment