import os import numpy as np from PIL import Image, ImageDraw, ImageFont import…
- User
import os import numpy as np from PIL import Image, ImageDraw, ImageFont import matplotlib.pyplot as plt import matplotlib.animation as animation import logging import argparse import random
Configure logging
logging.basicConfig( filename='process.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s' )
def log_and_print(message, level='info'): """Log and print messages.""" if level == 'info': logging.info(message) elif level == 'debug': logging.debug(message) elif level == 'error': logging.error(message) print(message)
def resize_image(image_path, new_size=(1024, 1024)): """Resize the image to a specified size.""" try: img = Image.open(image_path) # Handle PIL versions for resampling try: resample_method = Image.Resampling.LANCZOS except AttributeError: resample_method = Image.LANCZOS # For older PIL versions img = img.resize(new_size, resample=resample_method) resized_dir = 'resized_images' os.makedirs(resized_dir, exist_ok=True) base_name = os.path.splitext(os.path.basename(image_path))[0] resized_path = os.path.join(resized_dir, f"{base_name}_{new_size[0]}x{new_size[1]}.png") img.save(resized_path) log_and_print(f"Image resized and saved to {resized_path}") return resized_path except Exception as e: log_and_print(f"Error resizing image: {e}", 'error') return None
def read_text_from_file(file_path, image_size): """Read text message from a file and render it as an image.""" try: with open(file_path, 'r') as file: text_message = file.read().strip() log_and_print(f"Text message read from {file_path}: {text_message}")
code# Create a blank image with white background img_text = Image.new('RGB', image_size, color=(255, 255, 255)) draw = ImageDraw.Draw(img_text) # Choose a font size based on image size font_size = min(image_size) // 15 try: font = ImageFont.truetype("arial.ttf", font_size) # Adjust to available font path except IOError: font = ImageFont.load_default() log_and_print("Default font loaded. Truetype font not found.", 'error') # Get text size using textbbox method bbox = draw.textbbox((0, 0), text_message, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] # Calculate position to center the text position = ((image_size[0]-text_width)//2, (image_size[1]-text_height)//2) # Draw the text draw.text(position, text_message, fill=(0, 0, 0), font=font) log_and_print("Text image created successfully.") return np.array(img_text) except Exception as e: log_and_print(f"Error reading or rendering text: {e}", 'error') return None - Assistant