File size: 995 Bytes
a941c51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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