r3hab commited on
Commit
55b1a5a
·
verified ·
1 Parent(s): 8f0cebc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -0
app.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import os
4
+ import io
5
+ from tempfile import NamedTemporaryFile
6
+
7
+ def compress_image(image_file, output_path, target_size_kb, quality=75, step=5, min_quality=10, status_area=None):
8
+ """
9
+ Compresses an image to a target file size while maintaining reasonable quality.
10
+
11
+ Args:
12
+ image_file: An in-memory file object of the input image (when handling single image) or path to image.
13
+ output_path: Path to save the compressed image.
14
+ target_size_kb: Desired file size in kilobytes (approximate).
15
+ quality: Initial quality setting for compression (0-100, higher is better).
16
+ step: Step size to adjust quality during optimization.
17
+ min_quality: Minimum acceptable quality.
18
+ status_area: streamlit text area element to update user status
19
+
20
+ Returns:
21
+ True if compression was successful within the constraints, False otherwise.
22
+ """
23
+
24
+ try:
25
+ if isinstance(image_file, str): # Handle file paths
26
+ img = Image.open(image_file)
27
+ else: # Handle in-memory file objects (e.g. uploaded files)
28
+ img = Image.open(image_file)
29
+ except FileNotFoundError:
30
+ status_area.write(f"Error: Image not found at {image_file}") if status_area else print(f"Error: Image not found at {image_file}")
31
+ return False
32
+ except Exception as e:
33
+ status_area.write(f"Error opening image: {e}") if status_area else print(f"Error opening image: {e}")
34
+ return False
35
+
36
+ # Handle different image formats if needed
37
+ if img.format == "PNG":
38
+ # Convert PNG to RGB (remove alpha channel) to allow JPEG compression
39
+ if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
40
+ background = Image.new("RGB", img.size, (255, 255, 255))
41
+ background.paste(img, mask=img.split()[-1])
42
+ img = background
43
+
44
+ # Optimize for target size
45
+ while True:
46
+ try:
47
+ img.save(output_path, "JPEG", optimize=True, quality=quality)
48
+ except Exception as e:
49
+ status_area.write(f"Error saving image: {e}") if status_area else print(f"Error saving image: {e}")
50
+ return False
51
+
52
+ file_size_kb = os.path.getsize(output_path) / 1024
53
+
54
+ if file_size_kb <= target_size_kb or quality <= min_quality:
55
+ break
56
+
57
+ if file_size_kb > target_size_kb:
58
+ quality -= step
59
+ if quality < min_quality:
60
+ quality = min_quality
61
+
62
+ if file_size_kb <= target_size_kb:
63
+ status_area.write(f"Image compressed to {file_size_kb:.2f}KB (quality={quality})") if status_area else print(f"Image compressed to {file_size_kb:.2f}KB (quality={quality})")
64
+ return True
65
+ else:
66
+ status_area.write(f"Could not compress below {target_size_kb}KB within quality constraints.") if status_area else print(f"Could not compress below {target_size_kb}KB within quality constraints.")
67
+ return False
68
+
69
+
70
+ def batch_compress_images(files, output_dir, target_size_kb, status_area=None):
71
+ """
72
+ Compresses all images in a list.
73
+
74
+ Args:
75
+ files: A list of image file paths or in-memory files
76
+ output_dir: Directory to save compressed images.
77
+ target_size_kb: Target file size in kilobytes.
78
+ status_area: streamlit text area element to update user status
79
+ """
80
+ os.makedirs(output_dir, exist_ok=True)
81
+
82
+ for file in files:
83
+
84
+ if isinstance(file, str):
85
+ filename = os.path.basename(file)
86
+ else:
87
+ filename = file.name
88
+
89
+ if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
90
+ output_path = os.path.join(output_dir, filename)
91
+ success = compress_image(file, output_path, target_size_kb, status_area=status_area)
92
+ if not success:
93
+ status_area.write(f"Failed to compress {filename}") if status_area else print(f"Failed to compress {filename}")
94
+ else:
95
+ status_area.write(f"Skipping non-image file: {filename}") if status_area else print(f"Skipping non-image file: {filename}")
96
+
97
+ def main():
98
+ st.title("Image Compressor")
99
+
100
+ # Initialize session state
101
+ if "status_messages" not in st.session_state:
102
+ st.session_state.status_messages = []
103
+
104
+ status_area = st.empty() # Empty container to display status
105
+
106
+ st.header("Single Image Compression")
107
+ uploaded_file = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
108
+ target_size_single = st.number_input("Target Size (KB)", value=100)
109
+
110
+ col1, col2, col3 = st.columns(3)
111
+ with col1:
112
+ quality_single = st.number_input("Initial Quality", min_value=1, max_value=100, value=75)
113
+ with col2:
114
+ step_single = st.number_input("Quality Step", min_value=1, value=5)
115
+ with col3:
116
+ min_quality_single = st.number_input("Minimum Quality", min_value=1, max_value=100, value=10)
117
+
118
+ if uploaded_file:
119
+ if st.button("Compress Single Image"):
120
+
121
+ with NamedTemporaryFile(suffix=os.path.splitext(uploaded_file.name)[1], delete=False) as tmp_file:
122
+ tmp_file.write(uploaded_file.getvalue())
123
+ tmp_file_path = tmp_file.name
124
+
125
+ with NamedTemporaryFile(suffix=".jpg", delete=False) as temp_output_file:
126
+
127
+ success = compress_image(
128
+ tmp_file_path,
129
+ temp_output_file.name,
130
+ target_size_single,
131
+ quality_single,
132
+ step_single,
133
+ min_quality_single,
134
+ status_area
135
+ )
136
+ if success:
137
+ with open(temp_output_file.name, "rb") as f:
138
+ st.download_button(
139
+ label="Download Compressed Image",
140
+ data=f,
141
+ file_name=f"compressed_{os.path.splitext(uploaded_file.name)[0]}.jpg",
142
+ mime="image/jpeg"
143
+ )
144
+ os.remove(tmp_file_path)
145
+ os.remove(temp_output_file.name)
146
+
147
+ st.header("Batch Image Compression")
148
+ uploaded_files = st.file_uploader("Upload multiple images", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
149
+ target_size_batch = st.number_input("Target Size for Batch (KB)", value=150)
150
+
151
+ if uploaded_files:
152
+ if st.button("Compress Batch Images"):
153
+
154
+ temp_files = []
155
+ for file in uploaded_files:
156
+ with NamedTemporaryFile(suffix=os.path.splitext(file.name)[1], delete=False) as tmp_file:
157
+ tmp_file.write(file.getvalue())
158
+ temp_files.append(tmp_file.name)
159
+
160
+ with tempfile.TemporaryDirectory() as temp_dir:
161
+ batch_compress_images(temp_files, temp_dir, target_size_batch, status_area)
162
+
163
+ for file in temp_files:
164
+ os.remove(file)
165
+
166
+ for filename in os.listdir(temp_dir):
167
+ with open(os.path.join(temp_dir,filename), "rb") as f:
168
+ st.download_button(
169
+ label=f"Download Compressed {filename}",
170
+ data=f,
171
+ file_name=f"compressed_{filename}",
172
+ )
173
+
174
+
175
+ status_area.text_area("Status", value='\n'.join(st.session_state.status_messages), height=200)
176
+
177
+ if __name__ == "__main__":
178
+ import tempfile
179
+ main()