File size: 1,445 Bytes
a941c51
 
 
 
2d2877d
a941c51
2d2877d
a941c51
 
 
 
 
 
 
 
 
 
 
2d2877d
 
 
a941c51
2d2877d
 
a941c51
 
2d2877d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
33
34
35
36
37
38
39
40
41
42
43
44
45
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