from PIL import Image, ImageDraw, ImageFont def sub(p1, p2): return (p1[0] - p2[0], p1[1] - p2[1]) def overlay(image_in, message="YOU DIED", color=(200, 25, 25)): image = image_in.convert("RGBA") size = image.size center = (size[0]/2, size[1]/2) limit = size[1] if size[0] / size[1] < 1: limit = int(limit * size[0] / size[1]) font_size = limit // 5 gradient_range = limit // 10 rect_top = sub(center, (0, font_size * 3 // 5)) rect_bot = sub(center, (0, -font_size * 3 // 5)) overlay = Image.new("RGBA", size, (0,0,0,0)) draw = ImageDraw.Draw(overlay) font = ImageFont.truetype("OptimusPrinceps.ttf", font_size) draw.rectangle([0, rect_top[1], size[0], rect_bot[1]], fill=(0,0,0, 225)) for y in range(-1, -gradient_range - 1, -1): c = 225 - 225 * (-y) // gradient_range draw.line([0, rect_top[1] + y, size[0], rect_top[1] + y], fill=(0,0,0,c)) for y in range(1, gradient_range + 1, 1): c = 225 - 225 * (y) // gradient_range draw.line([0, rect_bot[1] + y, size[0], rect_bot[1] + y], fill=(0,0,0,c)) text_size = draw.textsize(message, font=font) # in case the text is too long ratio = text_size[0] / size[0] if ratio > 1: font = ImageFont.truetype("OptimusPrinceps.ttf", int(font_size / ratio)) text_size = draw.textsize(message, font=font) offset = (center[0] - text_size[0]/2, center[1] - text_size[1]/2) draw.text(offset, message, color, font=font) result = Image.alpha_composite(Image.alpha_composite(image, Image.new("RGBA", size, (0,0,0,125))), overlay) return result