Skip to content

Instantly share code, notes, and snippets.

@TheOnlyWayUp
Last active March 6, 2022 14:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheOnlyWayUp/460cf217f7b2e7e5f6a0117f25051d15 to your computer and use it in GitHub Desktop.
Save TheOnlyWayUp/460cf217f7b2e7e5f6a0117f25051d15 to your computer and use it in GitHub Desktop.
Example of BytesIO and PIL for modifying images without saving them
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