File size: 4,599 Bytes
6a8513b
 
66096c2
6a8513b
1d618a9
 
 
 
6a8513b
 
1d618a9
 
6a8513b
a68943c
1d618a9
 
6a8513b
1d618a9
6a8513b
 
1d618a9
 
a68943c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d618a9
a68943c
 
 
1d618a9
 
 
 
 
 
6a8513b
1d618a9
 
a68943c
 
 
 
 
 
 
 
 
6a8513b
a68943c
 
6a8513b
 
1d618a9
 
 
 
 
 
a68943c
6a8513b
a68943c
1d618a9
 
 
 
 
a68943c
 
 
 
1d618a9
 
 
6a8513b
a68943c
1d618a9
a68943c
 
 
 
 
 
 
1d618a9
 
a68943c
 
 
 
 
1d618a9
a68943c
1d618a9
 
 
a68943c
1d618a9
 
 
 
 
 
 
 
 
a68943c
 
1d618a9
 
 
 
 
 
 
 
 
 
 
a68943c
6a8513b
66096c2
 
1d618a9
6a8513b
1d618a9
 
 
6a8513b
1d618a9
6a8513b
1d618a9
6a8513b
66096c2
1d618a9
66096c2
 
 
6a8513b
66096c2
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
import io
from PIL import Image
import gradio as gr

def get_file_size_label(size_bytes):
    if size_bytes < 1024 * 1024:
        return f"{size_bytes / 1024:.1f} KB"
    return f"{size_bytes / (1024 * 1024):.2f} MB"


def compress_to_target(img, fmt, target_bytes):
    buf = io.BytesIO()

    # ---- PNG (NO format change) ----
    if fmt == "PNG":
        for level in range(1, 10):
            buf = io.BytesIO()
            img.save(buf, format="PNG", optimize=True, compress_level=level)
            if buf.tell() <= target_bytes:
                buf.seek(0)
                return buf, "PNG"

        # If cannot reach target β†’ return best effort PNG
        buf.seek(0)
        return buf, "PNG"

    # ---- JPEG ----
    elif fmt in ("JPEG", "JPG"):
        for q in range(95, 74, -2):
            buf = io.BytesIO()
            img.save(
                buf,
                format="JPEG",
                quality=q,
                optimize=True,
                subsampling=0 if q >= 85 else 2
            )
            if buf.tell() <= target_bytes:
                buf.seek(0)
                return buf, "JPEG"

        buf.seek(0)
        return buf, "JPEG"

    # ---- WEBP ----
    elif fmt == "WEBP":
        for q in range(95, 74, -2):
            buf = io.BytesIO()
            img.save(buf, format="WEBP", quality=q, method=6)
            if buf.tell() <= target_bytes:
                buf.seek(0)
                return buf, "WEBP"

        buf.seek(0)
        return buf, "WEBP"

    # ---- fallback ----
    else:
        img = img.convert("RGB")
        for q in range(95, 74, -2):
            buf = io.BytesIO()
            img.save(buf, format="JPEG", quality=q, optimize=True)
            if buf.tell() <= target_bytes:
                buf.seek(0)
                return buf, "JPEG"

        buf.seek(0)
        return buf, "JPEG"


def process_image(file, target_value, unit):
    if file is None:
        return None, "❌ Please upload an image"

    try:
        img = Image.open(file)
        fmt = (img.format or "JPEG").upper()

        # Normalize mode
        if img.mode in ("RGBA", "LA", "P"):
            if fmt == "JPEG":
                background = Image.new("RGB", img.size, (255, 255, 255))
                if img.mode == "P":
                    img = img.convert("RGBA")
                background.paste(
                    img,
                    mask=img.split()[-1] if img.mode in ("RGBA", "LA") else None
                )
                img = background
        elif img.mode not in ("RGB", "L"):
            img = img.convert("RGB")

        # Original size
        original_buf = io.BytesIO()
        if fmt == "PNG":
            img.save(original_buf, format="PNG")
        elif fmt == "WEBP":
            img.save(original_buf, format="WEBP")
        else:
            img.save(original_buf, format="JPEG", quality=95)

        original_size = original_buf.tell()

        target_bytes = (
            int(target_value * 1024)
            if unit == "KB"
            else int(target_value * 1024 * 1024)
        )

        # If already small
        if target_bytes >= original_size:
            return img, f"βœ… Already optimized: {get_file_size_label(original_size)}"

        # Compress
        compressed_buf, out_fmt = compress_to_target(img, fmt, target_bytes)
        compressed_size = compressed_buf.getbuffer().nbytes

        saved = max(0, original_size - compressed_size)
        pct = (saved / original_size) * 100

        result_msg = (
            f"πŸ“¦ Original: {get_file_size_label(original_size)}\n"
            f"πŸ—œοΈ Compressed: {get_file_size_label(compressed_size)}\n"
            f"πŸ’Ύ Saved: {pct:.1f}%\n"
            f"πŸ“ Format: {out_fmt}"
        )

        return Image.open(compressed_buf), result_msg

    except Exception as e:
        return None, f"❌ Error: {str(e)}"


# ---- UI ----
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# πŸ—œοΈ ImagePress β€” Smart Compressor")
    gr.Markdown("βœ” Preserves original format Β· βœ” No unwanted WEBP conversion")

    with gr.Row():
        input_img = gr.Image(type="filepath", label="Upload Image")
        output_img = gr.Image(label="Compressed Output")

    with gr.Row():
        target = gr.Number(value=200, label="Target Size")
        unit = gr.Radio(["KB", "MB"], value="KB", label="Unit")

    btn = gr.Button("⚑ Compress Image")

    result = gr.Textbox(label="Result")

    btn.click(
        fn=process_image,
        inputs=[input_img, target, unit],
        outputs=[output_img, result]
    )

demo.launch()