Spaces:
Sleeping
Sleeping
| from PIL import Image, ImageDraw, ImageFont | |
| import os | |
| from typing import Optional, Tuple, Dict, Any | |
| def add_text_to_image( | |
| image_path: str, | |
| text: str, | |
| color: Optional[Tuple[int, int, int]] = None, | |
| output_name: Optional[str] = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| Adds centered text to an image and saves the result in the same folder. | |
| If no output_name is provided, '_edited' is appended to the original filename. | |
| If no color is provided, black is used by default. | |
| Args: | |
| image_path: Path to the original image. | |
| text: Text to write on the image. | |
| color: Optional RGB color of the text. Defaults to black. | |
| output_name: Optional output filename (without extension). | |
| Returns: | |
| Dictionary with success status and info. | |
| """ | |
| try: | |
| if color is None: | |
| color = (0, 0, 0) | |
| image = Image.open(image_path) | |
| draw = ImageDraw.Draw(image) | |
| font = ImageFont.load_default() | |
| text_width = draw.textlength(text, font=font) | |
| x = (image.width - text_width) / 2 | |
| y = image.height / 2 | |
| draw.text((x, y), text, fill=color, font=font) | |
| base_dir = os.path.dirname(image_path) | |
| base_name, ext = os.path.splitext(os.path.basename(image_path)) | |
| if output_name: | |
| new_filename = f"{output_name}{ext}" | |
| else: | |
| new_filename = f"{base_name}_edited{ext}" | |
| new_path = os.path.join(base_dir, new_filename) | |
| image.save(new_path) | |
| output_size = os.path.getsize(new_path) | |
| return { | |
| "success": True, | |
| "message": "Text added successfully to the image", | |
| "input_path": image_path, | |
| "output_path": new_path, | |
| "output_size_bytes": output_size, | |
| "text": text, | |
| "color": color | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "error": str(e), | |
| "input_path": image_path, | |
| "output_path": None | |
| } | |