from PIL import Image | |
from io import BytesIO | |
import requests | |
import base64 | |
from typing import Union | |
def change_format(image: Union[str, BytesIO], 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. | |
""" | |
if not isinstance(image, BytesIO): | |
response = requests.get(image, 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 | |
else: | |
img = Image.open(image) | |
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 |