Last active
March 6, 2022 14:01
-
-
Save TheOnlyWayUp/460cf217f7b2e7e5f6a0117f25051d15 to your computer and use it in GitHub Desktop.
Example of BytesIO and PIL for modifying images without saving them
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
domain = 'watermark' # just an example of how to use bytesio with PIL, works better if you know more about the images you're using instead of using random ones which can have random dimensions. | |
import aiohttp | |
from urllib.parse import unquote | |
from io import BytesIO | |
from PIL import Image, ImageDraw, ImageFont | |
async def returnRandomCat(): | |
async with aiohttp.ClientSession() as session: | |
async with session.get("https://aws.random.cat/meow") as resp: | |
data = await resp.json() | |
url = unquote(data["file"]) | |
async with session.get(url) as resp: | |
data = await resp.read() | |
d = BytesIO(data) | |
d.seek(0) | |
img = Image.open(d) | |
draw = ImageDraw.Draw(img) | |
font = ImageFont.truetype("static/fonts/Roboto-Light.ttf", 20) | |
draw.text( | |
(img.width - font.getsize(domain)[0] - 200, img.height - 200), | |
domain, | |
fill=(255, 0, 255), | |
font=font, | |
) | |
# Put a border around the image | |
draw.rectangle((0, 0, img.width, img.height), outline=(255, 255, 255), width=5) | |
d.seek(0) | |
img.save(d, "PNG") | |
d.seek(0) | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment