Last active
June 30, 2023 11:34
-
-
Save yunruse/59528cea79c71988647811987b49769b to your computer and use it in GitHub Desktop.
Image that tells you your user agent
This file contains hidden or 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
#!/usr/bin/env python3 | |
"Image that dynamically tells you your user agent" | |
# save this as ./cgi-bin/index.png | |
# run python -m http.server --cgi | |
# go to http://localhost:8000/cgi-bin/hi.png | |
import os, sys | |
from PIL import Image, ImageDraw | |
def serve_png(io, file=sys.stdout): | |
# streamless beast. | |
file.write("Content-Type: image/png\n") | |
f = io.read() | |
file.write(f"Content-Length: {len(f)}\n\n") | |
file.flush() | |
file.buffer.write(f) | |
def get_font(*names, size=20): | |
# this is sloooow and needs a local cache. if you care | |
from PIL import ImageFont | |
from matplotlib import font_manager as fm | |
names = names or ['Helvetica', 'Arial'] | |
path = fm.findfont(fm.FontProperties(family=names)) | |
return ImageFont.truetype(path, size=size) | |
def chunk(seq, n: int): | |
for i in range(0, len(seq), n): yield seq[i:i+n] | |
AGENT = os.environ.get('HTTP_USER_AGENT', 'Unknown') | |
BG = '#EBDFB7'; FG = '#63476C'; W = 700; H = 100 | |
BIG = get_font('Calamity', size=20) | |
SMOL = get_font('Fantasque Sans Mono', size=14) | |
if __name__ == '__main__': | |
image = Image.new('RGB', (W, H)) | |
draw = ImageDraw.Draw(image) | |
draw.rectangle([0, 0, W, H], BG) | |
draw.text((10, 10), "Hey there! You're using", fill=FG, font=BIG) | |
for i, txt in enumerate(chunk(AGENT, 93)): | |
draw.text((10, 20 + 15*(i+1)), txt, fill=FG, font=SMOL) | |
image.save('tmp.png') | |
with open('tmp.png', 'rb') as f: | |
serve_png(f) | |
# os.unlink('tmp.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment