File size: 3,899 Bytes
e9c9cb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import numpy as np
from PIL import Image, ImageOps
import io
import base64

def resize_image(image, max_size=1024):
    """
    Resize image to maximum dimension while maintaining aspect ratio.
    
    Args:
        image (PIL.Image): Input image
        max_size (int): Maximum dimension size
    
    Returns:
        PIL.Image: Resized image
    """
    if image is None:
        return None
    
    # Get current dimensions
    width, height = image.size
    
    # Calculate new dimensions
    if max(width, height) > max_size:
        if width > height:
            new_width = max_size
            new_height = int(height * max_size / width)
        else:
            new_height = max_size
            new_width = int(width * max_size / height)
        
        image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
    
    return image

def convert_to_rgba(image):
    """
    Convert image to RGBA format with transparency.
    
    Args:
        image (PIL.Image): Input image
    
    Returns:
        PIL.Image: RGBA image
    """
    if image is None:
        return None
    
    if image.mode != 'RGBA':
        image = image.convert('RGBA')
    
    return image

def image_to_base64(image):
    """
    Convert PIL image to base64 string.
    
    Args:
        image (PIL.Image): Input image
    
    Returns:
        str: Base64 encoded image
    """
    if image is None:
        return None
    
    buffer = io.BytesIO()
    image.save(buffer, format='PNG')
    buffer.seek(0)
    
    return base64.b64encode(buffer.getvalue()).decode('utf-8')

def base64_to_image(base64_string):
    """
    Convert base64 string to PIL image.
    
    Args:
        base64_string (str): Base64 encoded image
    
    Returns:
        PIL.Image: Decoded image
    """
    if base64_string is None:
        return None
    
    try:
        image_bytes = base64.b64decode(base64_string)
        return Image.open(io.BytesIO(image_bytes))
    except Exception as e:
        raise ValueError(f"Invalid base64 image data: {str(e)}")

def validate_image(image):
    """
    Validate that the input is a proper image.
    
    Args:
        image: Input to validate
    
    Returns:
        bool: True if valid image
    """
    if image is None:
        return False
    
    try:
        if isinstance(image, np.ndarray):
            image = Image.fromarray(image)
        
        if hasattr(image, 'save'):
            # Test if image can be saved
            buffer = io.BytesIO()
            image.save(buffer, format='PNG')
            return True
        
        return False
    except Exception:
        return False

def create_transparent_background(image, color=(255, 255, 255)):
    """
    Replace transparent areas with specified color.
    
    Args:
        image (PIL.Image): Input image
        color (tuple): RGB color to use as background
    
    Returns:
        PIL.Image: Image with colored background
    """
    if image is None:
        return None
    
    # Ensure image is RGBA
    if image.mode != 'RGBA':
        image = image.convert('RGBA')
    
    # Create background
    background = Image.new('RGB', image.size, color)
    background.paste(image, mask=image.split()[-1])  # Use alpha channel as mask
    
    return background

def optimize_for_web(image, quality=85):
    """
    Optimize image for web use.
    
    Args:
        image (PIL.Image): Input image
        quality (int): JPEG quality (1-100)
    
    Returns:
        PIL.Image: Optimized image
    """
    if image is None:
        return None
    
    # Convert to RGB if no transparency
    if image.mode in ('RGBA', 'LA') and 'transparency' not in image.info:
        background = Image.new('RGB', image.size, (255, 255, 255))
        background.paste(image, mask=image.split()[-1] if image.mode == 'RGBA' else None)
        image = background
    
    return image