Certainly! Below is a Python program that calculates a specified number of π (pi) digits and places them onto one or more A4-sized images. The program ensures that the text densely fills each page by adjusting the font size dynamically. If the required font size becomes too small to be effectively rendered by a typical printer, the program automatically splits the digits across multiple A4 images.
Key Features:
- Pi Digit Calculation: Uses the
mpmath library to compute π to a high number of decimal places.
- Dynamic Font Sizing: Determines the maximum possible font size that allows all digits to fit onto an A4 page. If this size becomes impractically small, the digits are split across multiple images.
- Image Generation: Utilizes the
Pillow library to create A4-sized images (2480 x 3508 pixels at 300 DPI) and places the digits onto these images.
- Deprecation Compliance: Replaces deprecated
getsize with getbbox to measure text dimensions, ensuring compatibility with future Pillow versions.
Prerequisites:
Complete Code:
import mpmath
from PIL import Image, ImageDraw, ImageFont
import math
import os
def get_pi_digits(n):
"""
Calculate n digits of pi using mpmath.
Args:
n (int): Number of pi digits to calculate.
Returns:
str: A string containing n digits of pi (without the initial '3.').
"""
mpmath.mp.dps = n + 2 # Decimal places; 1 extra for '3.'
pi_str = str(mpmath.mp.pi)
pi_digits = pi_str.replace('.', '')[:n]
return pi_digits
def find_font_size_and_capacity(font_path, image_width, image_height, digits):
"""
Find the largest font size that allows a given number of digits to fit into the image.
Args:
font_path (str): Path to the TTF font file.
image_width (int): Width of the image in pixels.
image_height (int): Height of the image in pixels.
digits (int): Number of digits to fit.
Returns:
tuple: (font_size, capacity)
font_size (int): Suitable font size.
capacity (int): Number of digits that can fit with this font size.
"""
lower = 1
upper = 500 # Arbitrary upper limit for font size
best_font_size = None
best_capacity = 0
while lower <= upper:
mid = (lower + upper) // 2
try:
font = ImageFont.truetype(font_path, mid)
except IOError:
# Font size not supported
upper = mid - 1
continue
# Measure character size using '0' as a representative character
bbox = font.getbbox('0')
char_width = bbox[2] - bbox[0]
char_height = bbox[3] - bbox[1]
if char_width == 0 or char_height == 0:
upper = mid - 1
continue
# Calculate how many characters fit per line and number of lines
chars_per_line = image_width // char_width
lines = image_height // char_height
capacity = chars_per_line * lines
if capacity >= digits and chars_per_line > 0 and lines > 0:
best_font_size = mid
best_capacity = capacity
lower = mid + 1 # Try a larger font size
else:
upper = mid - 1 # Try a smaller font size
if best_font_size:
return best_font_size, best_capacity
else:
# If no suitable font size found, use the smallest possible
font_size = 1
try:
font = ImageFont.truetype(font_path, font_size)
except IOError:
raise ValueError("Font loading failed. Please check the font path.")
bbox = font.getbbox('0')
char_width = bbox[2] - bbox[0]
char_height = bbox[3] - bbox[1]
chars_per_line = image_width // char_width
lines = image_height // char_height
capacity = chars_per_line * lines
return font_size, capacity
def create_pi_images(pi_digits, font_path, image_width=2480, image_height=3508):
"""
Create one or more A4-sized images containing the pi digits.
Args:
pi_digits (str): String of pi digits.
font_path (str): Path to the TTF font file.
image_width (int, optional): Width of the image in pixels. Defaults to 2480 (A4 at 300 DPI).
image_height (int, optional): Height of the image in pixels. Defaults to 3508 (A4 at 300 DPI).
Returns:
list: A list of PIL Image objects.
"""
images = []
digits_remaining = pi_digits
while digits_remaining:
digits_count = len(digits_remaining)
font_size, capacity = find_font_size_and_capacity(font_path, image_width, image_height, digits_count)
if capacity == 0:
raise ValueError("Cannot fit any digits into the image with the given parameters.")
# Extract the chunk of digits for the current image
chunk = digits_remaining[:capacity]
digits_remaining = digits_remaining[capacity:]
# Create a new white image
img = Image.new('RGB', (image_width, image_height), color='white')
draw = ImageDraw.Draw(img)
# Load the font with the determined size
font = ImageFont.truetype(font_path, font_size)
# Measure character dimensions
bbox = font.getbbox('0')
char_width = bbox[2] - bbox[0]
char_height = bbox[3] - bbox[1]
# Calculate characters per line and number of lines
chars_per_line = image_width // char_width
lines = image_height // char_height
# Split the chunk into lines
lines_list = [chunk[i:i+chars_per_line] for i in range(0, len(chunk), chars_per_line)]
# Draw each line onto the image
y = 0
for line in lines_list:
draw.text((0, y), line, font=font, fill='black')
y += char_height
images.append(img)
return images
def save_images(images, output_folder):
"""
Save the generated images to the specified folder.
Args:
images (list): List of PIL Image objects.
output_folder (str): Directory where images will be saved.
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for idx, img in enumerate(images):
img_path = os.path.join(output_folder, f'pi_digits_page_{idx+1}.png')
# Save with 300 DPI
img.save(img_path, 'PNG', dpi=(300, 300))
print(f"Saved {img_path}")
def main():
"""
Main function to execute the pi digit image generation.
"""
# User-configurable parameters
n_digits = 100000 # Number of pi digits to calculate
font_path = '/path/to/DejaVuSansMono.ttf' # Update this path to your monospaced TTF font
image_width = 2480 # A4 width in pixels at 300 DPI
image_height = 3508 # A4 height in pixels at 300 DPI
output_folder = 'pi_images' # Output directory for images
# Step 1: Calculate pi digits
print(f"Calculating {n_digits} digits of pi...")
pi_digits = get_pi_digits(n_digits)
print("Pi digit calculation complete.")
# Step 2: Create images with pi digits
print("Generating image(s) with pi digits...")
images = create_pi_images(pi_digits, font_path, image_width, image_height)
print(f"Generated {len(images)} image(s).")
# Step 3: Save the images
print("Saving images...")
save_images(images, output_folder)
print("All images have been saved successfully.")
if __name__ == "__main__":
main()
How It Works:
-
Pi Calculation (get_pi_digits):
- Uses
mpmath to calculate π to n decimal places.
- Extracts the digits after the decimal point, omitting the initial '3'.
-
Font Size and Capacity Determination (find_font_size_and_capacity):
- Performs a binary search to find the largest possible font size that allows a given number of digits (
digits) to fit within the A4 image dimensions.
- If no suitable font size is found to fit all digits on one image, it defaults to the smallest font size and calculates how many digits can fit.
-
Image Creation (create_pi_images):
- Iteratively processes the pi digits, creating new images as necessary.
- For each image, it determines the appropriate font size and how many digits can fit.
- Splits the digits into lines based on the calculated characters per line and number of lines.
- Draws the digits onto the image using the determined font size.
-
Saving Images (save_images):
- Saves each generated image as a PNG file in the specified output directory.
- Sets the DPI to
300 to ensure high-quality printing.
-
Main Execution (main):
- Sets the parameters such as number of digits, font path, image dimensions, and output folder.
- Executes the steps to calculate pi digits, generate images, and save them.
Important Notes:
-
Font Path: Replace '/path/to/DejaVuSansMono.ttf' with the actual path to your monospaced TTF font on your device. On PyDroid, the font might be located in a specific directory. You can place the font file in the same directory as your script and set font_path = 'DejaVuSansMono.ttf'.
-
Number of Digits (n_digits): Adjust this value based on how many pi digits you want. Keep in mind that very large numbers (e.g., millions) may require significant memory and processing time, especially on mobile devices.
-
Output Directory: The images will be saved in the pi_images folder relative to where the script is run. Ensure that the script has write permissions to this directory.
-
DPI Setting: The images are saved with a DPI of 300. If you wish to change the DPI, adjust the dpi parameter in the img.save method.
-
Deprecation Handling: The script uses font.getbbox('0') to measure the dimensions of a single digit, complying with Pillow's updated practices and avoiding the deprecated getsize method.
Running the Program:
-
Ensure Dependencies Are Installed:
pip install mpmath Pillow
-
Place the Font File:
- Ensure that the monospaced TTF font (e.g.,
DejaVuSansMono.ttf) is accessible to the script. Place it in the same directory or provide the absolute path.
-
Execute the Script:
python pi_image_generator.py
Replace pi_image_generator.py with the name you've given to the script.
-
Output:
- The generated images will be saved in the
pi_images folder. Each image will be named pi_digits_page_1.png, pi_digits_page_2.png, etc., depending on how many images were created.
Sample Output:
Calculating 100000 digits of pi...
Pi digit calculation complete.
Generating image(s) with pi digits...
Generated 4 image(s).
Saving images...
Saved pi_images/pi_digits_page_1.png
Saved pi_images/pi_digits_page_2.png
Saved pi_images/pi_digits_page_3.png
Saved pi_images/pi_digits_page_4.png
All images have been saved successfully.
Each image will contain a dense grid of pi digits, correctly filling the A4 page dimensions. If all digits cannot fit on a single page at a reasonable font size, the program splits them across multiple images, ensuring that each page remains clear and printable.
Customization:
-
Adjusting Image Quality: You can modify the image_width and image_height if you prefer a different DPI or page size. Remember that 2480x3508 pixels correspond to A4 size at 300 DPI.
-
Changing Output Format: The script saves images in PNG format, but you can change 'PNG' to 'JPEG' or another supported format in the img.save method if desired.
-
Error Handling: The script includes basic error handling for font loading and image capacity issues. You can expand upon these to include more robust logging or user prompts as needed.
I hope this helps you generate high-density pi digit images tailored to your printing needs! If you encounter any issues or have further questions, feel free to ask.