Created
February 16, 2025 04:25
-
-
Save yeiichi/6db0a224f39db1f7e1c6d5bef509e0fc to your computer and use it in GitHub Desktop.
Create a blank PNG image with a test string—A code written by ChatGPT o3-mini-high.
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 | |
from PIL import Image, ImageDraw, ImageFont | |
""" | |
Create a blank PNG image with a test string—A code written by ChatGPT o3-mini-high. | |
This script is created by ChatGPT o3-mini-high with the following prompt: | |
Objective: Write a Python code that creates a PNG file. | |
Specification: | |
- Ask the user for the dimension of the image. | |
- Ask the user for a test string to display in the center of the image. | |
- Python 3.12.2 compatible. | |
- Pillow 10.2.0 compatible. | |
Changes made by ChatGPT o3-mini-high: | |
- Replaced draw.textsize() with draw.textbbox() to calculate the text dimensions | |
in Pillow 10.2.0. | |
- The bounding box coordinates (bbox) are used to calculate the width and height | |
of the text, which helps center it properly. | |
This should work without any errors in Pillow 10.2.0 and Python 3.12.2. | |
""" | |
# Ask the user for the image dimensions | |
width = int(input("Enter the width of the image (in pixels): ")) | |
height = int(input("Enter the height of the image (in pixels): ")) | |
# Ask the user for the test string to display in the center of the image | |
text = input("Enter the text to display in the center of the image: ") | |
# Create a new image with the specified dimensions and a white background | |
image = Image.new("RGB", (width, height), "white") | |
# Initialize ImageDraw to draw on the image | |
draw = ImageDraw.Draw(image) | |
# Try to load a basic font; if unavailable, fall back to a default one | |
try: | |
font = ImageFont.truetype("arial.ttf", 40) | |
except IOError: | |
font = ImageFont.load_default() | |
# Calculate the bounding box of the text to center it | |
bbox = draw.textbbox((0, 0), text, font=font) | |
text_width = bbox[2] - bbox[0] | |
text_height = bbox[3] - bbox[1] | |
# Calculate the position to center the text | |
x_position = (width - text_width) // 2 | |
y_position = (height - text_height) // 2 | |
# Draw the text in the center of the image | |
draw.text((x_position, y_position), text, font=font, fill="black") | |
# Save the image to a PNG file | |
image.save("test_image.png") | |
print("Image created and saved as 'test_image.png'.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment