Created
September 4, 2024 19:15
-
-
Save Melvillian/cb87f3f34ba4049edce54c8e52bf2d02 to your computer and use it in GitHub Desktop.
short and sweet code for downloading a jpg from the internet and making a meme with text from it. Requires you download impact.ttf font (which is free)
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
| import requests | |
| from PIL import Image, ImageDraw, ImageFont | |
| from io import BytesIO | |
| def draw_caption_internal(image, caption, where, is_bottom): | |
| text_bbox = draw.textbbox((0, 0), caption, font=font) | |
| text_width = text_bbox[2] - text_bbox[0] | |
| text_height = text_bbox[3] - text_bbox[1] | |
| # Calculate X, Y position of the text | |
| y_offset = 0 | |
| if is_bottom: | |
| y_offset = image.height - (text_height + where) | |
| else: | |
| y_offset = where | |
| x = (image.width - text_width) / 2 | |
| y = y_offset | |
| draw.text((x, y), caption, font=font, fill="white") | |
| def draw_caption_bottom(image, caption, where): | |
| draw_caption_internal(image, caption, where, True) | |
| def draw_caption_top(image, caption, where): | |
| draw_caption_internal(image, caption, where, False) | |
| # URL of the image | |
| image_url = "https://stephencwinter.com/wp-content/uploads/2023/07/5mof3hn1byf7gtf-oo1fjkv1h7kspa2ly0jntdvuukk.jpg?w=768" | |
| # Download the image | |
| response = requests.get(image_url) | |
| image = Image.open(BytesIO(response.content)) | |
| # Create a drawing context | |
| draw = ImageDraw.Draw(image) | |
| # Define the font and size (you may need to specify the path to a .ttf file on your system) | |
| font_size = 80 | |
| try: | |
| font = ImageFont.truetype("impact.ttf", font_size) | |
| except IOError: | |
| font = ImageFont.load_default(font_size) | |
| draw_caption_top(image, "my king would", 0) | |
| draw_caption_top(image, "remember his", 80) | |
| draw_caption_top(image, "old strength", 160) | |
| draw_caption_bottom(image, "if he grasped", 100) | |
| draw_caption_bottom(image, "his sword", 30) | |
| # Save the edited image | |
| output_image_path = "image_with_caption.jpg" | |
| image.save(output_image_path) | |
| print(f"Image saved as {output_image_path}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment