Spaces:
Sleeping
Sleeping
| from PIL import Image | |
| from io import BytesIO | |
| import requests | |
| import base64 | |
| def change_format(image_url: str, target_format: str) -> str: | |
| """ | |
| Change the format of an image from a URL to the specified target format. | |
| Args: | |
| image_url: The URL of the input image. | |
| target_format: The desired output format (e.g., 'JPEG', 'PNG'). | |
| Returns: | |
| The image converted to the target format as a base64-encoded string. | |
| """ | |
| response = requests.get(image_url, timeout=30) | |
| response.raise_for_status() | |
| # Open the image from bytes | |
| img = Image.open(BytesIO(response.content)) | |
| # Convert the image to the target format | |
| output = BytesIO() | |
| img.save(output, format=target_format) | |
| output.seek(0) | |
| # Convert to base64 string for JSON serialization | |
| encoded_image = base64.b64encode(output.getvalue()).decode('utf-8') | |
| return encoded_image # Return base64 encoded string that can be serialized to JSON |