🔍 Code Extractor

function create_test_image

Maturity: 47

Creates a synthetic test image with text rendered in a handwritten-style font on a white background and saves it to disk.

File:
/tf/active/vicechatdev/e-ink-llm/test.py
Lines:
19 - 44
Complexity:
simple

Purpose

This function generates test images containing text for testing OCR, handwriting recognition, or image processing systems. It creates an 800x600 pixel white canvas and renders the provided text using a TrueType font (preferring Liberation Sans, falling back to Arial, then default font). The text is split by newlines and rendered with 40-pixel vertical spacing. Primarily used for creating mock handwritten documents or testing e-ink display processors.

Source Code

def create_test_image(text: str, filename: str):
    """Create a simple test image with handwritten-style text"""
    # Create a white image
    img = Image.new('RGB', (800, 600), color='white')
    draw = ImageDraw.Draw(img)
    
    # Try to use a more handwritten-like font, fall back to default if not available
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", 24)
    except:
        try:
            font = ImageFont.truetype("arial.ttf", 24)
        except:
            font = ImageFont.load_default()
    
    # Draw the text
    lines = text.split('\n')
    y_position = 50
    
    for line in lines:
        draw.text((50, y_position), line, fill='black', font=font)
        y_position += 40
    
    # Save the image
    img.save(filename)
    print(f"✅ Created test image: {filename}")

Parameters

Name Type Default Kind
text str - positional_or_keyword
filename str - positional_or_keyword

Parameter Details

text: The text content to render on the image. Can contain newline characters (\n) to create multiple lines. Each line will be rendered 40 pixels below the previous one, starting at y-position 50. Expected to be a string of any length, though very long text may exceed image boundaries.

filename: The file path where the generated image will be saved. Should include the file extension (e.g., '.png', '.jpg'). The function uses PIL's save method, so any format supported by PIL is valid. Can be a relative or absolute path.

Return Value

This function returns None. It performs side effects by creating and saving an image file to disk and printing a success message to stdout in the format '✅ Created test image: {filename}'.

Dependencies

  • PIL
  • Pillow

Required Imports

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

Usage Example

from PIL import Image, ImageDraw, ImageFont

def create_test_image(text: str, filename: str):
    img = Image.new('RGB', (800, 600), color='white')
    draw = ImageDraw.Draw(img)
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", 24)
    except:
        try:
            font = ImageFont.truetype("arial.ttf", 24)
        except:
            font = ImageFont.load_default()
    lines = text.split('\n')
    y_position = 50
    for line in lines:
        draw.text((50, y_position), line, fill='black', font=font)
        y_position += 40
    img.save(filename)
    print(f"✅ Created test image: {filename}")

# Example usage
test_text = "Hello World\nThis is a test\nHandwritten style text"
create_test_image(test_text, "test_output.png")

Best Practices

  • Ensure the output directory exists before calling this function, as it does not create parent directories
  • Be aware that text exceeding the image dimensions (800x600) will be clipped and not visible
  • The function uses try-except blocks for font loading, so it will always succeed in loading some font, but the visual appearance may vary across systems
  • Consider the number of lines in your text: with 40-pixel spacing and starting at y=50, approximately 13-14 lines will fit within the 600-pixel height
  • The function prints to stdout, which may not be desirable in production environments; consider capturing or suppressing output if needed
  • File format is determined by the filename extension; use common formats like .png, .jpg, or .bmp for best compatibility

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_handwritten_question 72.7% similar

    Generates a synthetic handwritten-style question image about photosynthesis with formatted text and decorative elements, saved as a PNG file.

    From: /tf/active/vicechatdev/e-ink-llm/demo.py
  • function create_test_document 62.4% similar

    Creates a text file at the specified path with the given content, primarily used for testing purposes.

    From: /tf/active/vicechatdev/docchat/test_incremental_indexing.py
  • function create_test_file 59.4% similar

    Creates a temporary text file with predefined multi-chapter test content for testing document extraction and processing functionality.

    From: /tf/active/vicechatdev/vice_ai/test_extraction_debug.py
  • class SignatureGenerator 58.1% similar

    A class that generates signature-like images from text names using italic fonts and decorative flourishes.

    From: /tf/active/vicechatdev/document_auditor/src/utils/signature_generator.py
  • function create_signature_image 56.4% similar

    Generates a synthetic signature image for a given name, either as stylized text or as a random hand-drawn curve, and saves it as a PNG file with transparent background.

    From: /tf/active/vicechatdev/document_auditor/generate_sample_signatures.py
← Back to Browse