|
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() |
|
|
|
|
|
img = Image.open(BytesIO(response.content)) |
|
|
|
|
|
output = BytesIO() |
|
img.save(output, format=target_format) |
|
output.seek(0) |
|
|
|
|
|
encoded_image = base64.b64encode(output.getvalue()).decode('utf-8') |
|
|
|
return encoded_image |
|
else: |
|
img = Image.open(image) |
|
|
|
output = BytesIO() |
|
img.save(output, format=target_format) |
|
output.seek(0) |
|
|
|
|
|
encoded_image = base64.b64encode(output.getvalue()).decode('utf-8') |
|
|
|
return encoded_image |