imgbytesizer 0.2.4__tar.gz → 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: imgbytesizer
3
- Version: 0.2.4
3
+ Version: 0.2.5
4
4
  Summary: A CLI tool to resize images to a target file size.
5
5
  License: MIT
6
6
  Keywords: image,resize,compression,cli,optimize
@@ -24,6 +24,7 @@ Description-Content-Type: text/markdown
24
24
  [![PyPI version](https://img.shields.io/pypi/v/imgbytesizer.svg)](https://pypi.org/project/imgbytesizer/)
25
25
  [![PyPI Downloads](https://static.pepy.tech/badge/imgbytesizer)](https://pepy.tech/projects/imgbytesizer)
26
26
  [![codecov](https://codecov.io/gh/pyyupsk/imgbytesizer/graph/badge.svg?token=GJH6N3ZAJS)](https://codecov.io/gh/pyyupsk/imgbytesizer)
27
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=pyyupsk_imgbytesizer&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=pyyupsk_imgbytesizer)
27
28
 
28
29
  ImgByteSizer is a command-line tool that precisely resizes and optimizes images to match a specific file size while maintaining the best possible quality.
29
30
 
@@ -3,6 +3,7 @@
3
3
  [![PyPI version](https://img.shields.io/pypi/v/imgbytesizer.svg)](https://pypi.org/project/imgbytesizer/)
4
4
  [![PyPI Downloads](https://static.pepy.tech/badge/imgbytesizer)](https://pepy.tech/projects/imgbytesizer)
5
5
  [![codecov](https://codecov.io/gh/pyyupsk/imgbytesizer/graph/badge.svg?token=GJH6N3ZAJS)](https://codecov.io/gh/pyyupsk/imgbytesizer)
6
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=pyyupsk_imgbytesizer&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=pyyupsk_imgbytesizer)
6
7
 
7
8
  ImgByteSizer is a command-line tool that precisely resizes and optimizes images to match a specific file size while maintaining the best possible quality.
8
9
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "imgbytesizer"
3
- version = "0.2.4"
3
+ version = "0.2.5"
4
4
  description = "A CLI tool to resize images to a target file size."
5
5
  keywords = ["image", "resize", "compression", "cli", "optimize"]
6
6
 
@@ -2,6 +2,6 @@
2
2
  imgbytesizer: A CLI tool to resize images to a target file size.
3
3
  """
4
4
 
5
- __version__: str = "0.2.4"
5
+ __version__: str = "0.2.5"
6
6
  __author__: str = "pyyupsk"
7
7
  __description__: str = "Resize images to match a target file size"
@@ -7,7 +7,7 @@ import logging
7
7
  import os
8
8
  import time
9
9
  from pathlib import Path
10
- from typing import Final, Optional, Tuple, Union
10
+ from typing import Optional, Tuple, Union
11
11
 
12
12
  from PIL import Image, ImageFile
13
13
 
@@ -24,19 +24,9 @@ ImageFile.LOAD_TRUNCATED_IMAGES = True
24
24
  logger: logging.Logger = logging.getLogger("imgbytesizer")
25
25
 
26
26
 
27
- def resize_to_target_filesize(
28
- image_path: Union[str, Path],
29
- target_size_bytes: int,
30
- output_path: Optional[str] = None,
31
- format_name: Optional[str] = None,
32
- min_dimension: Optional[int] = None,
33
- exact_size: bool = True,
34
- quiet: bool = False,
35
- ) -> str:
36
- """Resize an image to match a target file size in bytes."""
37
- start_time: float = time.time()
38
-
39
- # Load the image and get original info
27
+ def _setup_image(image_path: Union[str, Path],
28
+ quiet: bool = False) -> Tuple[Image.Image, int, int, int]:
29
+ """Load image and get original info."""
40
30
  print_processing_step(
41
31
  0, f"Opening {Colors.YELLOW}{os.path.basename(str(image_path))}{Colors.ENDC}"
42
32
  )
@@ -51,55 +41,57 @@ def resize_to_target_filesize(
51
41
  orig_width: int
52
42
  orig_height: int
53
43
  orig_width, orig_height = img.size
44
+ orig_size: int = os.path.getsize(image_path)
54
45
 
55
- # Normalize format names and determine output path
56
- pil_format: str = get_output_format(img.format or "JPEG", format_name)
57
- output_path = get_output_path(image_path, output_path, pil_format)
58
-
59
- # Print image information if not in quiet mode
60
46
  if not quiet:
61
47
  print_result("File", os.path.basename(str(image_path)))
62
- print_result("Format", pil_format)
63
48
  print_result("Dimensions", f"{orig_width} × {orig_height} pixels")
64
-
65
- orig_size: int = os.path.getsize(image_path)
66
49
  print_result("Size", format_filesize(orig_size))
67
- print_result("Target size", format_filesize(target_size_bytes))
68
- else:
69
- # Even in quiet mode, we need the original size
70
- orig_size: int = os.path.getsize(image_path)
71
50
 
72
- # Check if resizing is needed
73
- if orig_size <= target_size_bytes:
74
- if not quiet:
75
- print(f"{Colors.GREEN}✓ Original image is already smaller than target size{Colors.ENDC}")
51
+ return img, orig_width, orig_height, orig_size
76
52
 
77
- # If format conversion is needed
78
- if format_name and format_name.upper() != img.format:
79
- img.save(output_path)
80
- if not quiet:
81
- print_result("Status", "Converted format only", "good")
82
- print_result("Output", os.path.basename(output_path))
83
- else:
84
- # No processing needed, just copy
85
- from shutil import copy2
86
53
 
87
- copy2(image_path, output_path)
88
- if not quiet:
89
- print_result("Status", "No processing needed", "good")
90
- print_result("Output", os.path.basename(output_path))
54
+ def _handle_format_conversion(
55
+ img: Image.Image,
56
+ image_path: str,
57
+ output_path: str,
58
+ format_name: Optional[str],
59
+ quiet: bool = False
60
+ ) -> str:
61
+ """Handle format conversion if needed."""
62
+ if format_name and format_name.upper() != img.format:
63
+ img.save(output_path)
64
+ if not quiet:
65
+ print_result("Status", "Converted format only", "good")
66
+ print_result("Output", os.path.basename(output_path))
67
+ else:
68
+ # No processing needed, just copy
69
+ from shutil import copy2
70
+ copy2(image_path, output_path)
71
+ if not quiet:
72
+ print_result("Status", "No processing needed", "good")
73
+ print_result("Output", os.path.basename(output_path))
74
+ return output_path
91
75
 
92
- return output_path
93
76
 
94
- # For formats that support quality adjustment, try that first
77
+ def _select_resizing_strategy(
78
+ img: Image.Image,
79
+ pil_format: str,
80
+ target_size_bytes: int,
81
+ output_path: str,
82
+ orig_width: int,
83
+ orig_height: int,
84
+ min_dimension: Optional[int],
85
+ quiet: bool = False
86
+ ) -> str:
87
+ """Select and execute appropriate resizing strategy."""
95
88
  if pil_format in ["JPEG", "WEBP"]:
96
89
  # First, try quality adjustment with original dimensions
97
90
  result: Optional[str] = _try_quality_adjustment(
98
91
  img, pil_format, target_size_bytes, output_path, quiet
99
92
  )
100
93
 
101
- # If quality adjustment alone doesn't work (image too small),
102
- # try combined approach with resizing
94
+ # If quality adjustment alone doesn't work, try combined approach
103
95
  if result is None or os.path.getsize(result) < target_size_bytes * 0.9:
104
96
  result = _try_combined_approach(
105
97
  img,
@@ -123,25 +115,73 @@ def resize_to_target_filesize(
123
115
  min_dimension,
124
116
  quiet,
125
117
  )
118
+ return result
119
+
120
+
121
+ def _adjust_final_size(
122
+ output_path: str,
123
+ target_size_bytes: int,
124
+ pil_format: str,
125
+ exact_size: bool,
126
+ quiet: bool = False
127
+ ) -> None:
128
+ """Adjust final size to match target if needed."""
129
+ if not exact_size or not os.path.exists(output_path):
130
+ return
131
+
132
+ current_size: int = os.path.getsize(output_path)
133
+ if current_size < target_size_bytes:
134
+ _adjust_to_exact_size(output_path, target_size_bytes, quiet)
135
+ elif current_size > target_size_bytes and pil_format in ["JPEG", "WEBP"]:
136
+ if not quiet:
137
+ print("File is larger than target, adjusting quality once more...")
138
+ _final_quality_adjustment(output_path, pil_format, target_size_bytes, quiet)
139
+
140
+
141
+ def resize_to_target_filesize(
142
+ image_path: Union[str, Path],
143
+ target_size_bytes: int,
144
+ output_path: Optional[str] = None,
145
+ format_name: Optional[str] = None,
146
+ min_dimension: Optional[int] = None,
147
+ exact_size: bool = True,
148
+ quiet: bool = False,
149
+ ) -> str:
150
+ """Resize an image to match a target file size in bytes."""
151
+ start_time: float = time.time()
152
+
153
+ # Load image and get original info
154
+ img, orig_width, orig_height, orig_size = _setup_image(image_path, quiet)
155
+
156
+ # Normalize format names and determine output path
157
+ pil_format: str = get_output_format(img.format or "JPEG", format_name)
158
+ output_path = get_output_path(image_path, output_path, pil_format)
159
+
160
+ if not quiet:
161
+ print_result("Format", pil_format)
162
+ print_result("Target size", format_filesize(target_size_bytes))
163
+
164
+ # Check if resizing is needed
165
+ if orig_size <= target_size_bytes:
166
+ if not quiet:
167
+ print(f"{Colors.GREEN}✓ Original image is already smaller than target size{Colors.ENDC}")
168
+ return _handle_format_conversion(img, str(image_path), output_path, format_name, quiet)
126
169
 
127
- # Fine-tuning to match exact target size if needed
128
- if exact_size and os.path.exists(output_path):
129
- current_size: int = os.path.getsize(output_path)
130
- if current_size < target_size_bytes:
131
- _adjust_to_exact_size(output_path, target_size_bytes, quiet)
132
- elif current_size > target_size_bytes and pil_format in ["JPEG", "WEBP"]:
133
- # If we somehow overshot, try one more quality adjustment
134
- if not quiet:
135
- print("File is larger than target, adjusting quality once more...")
136
- _final_quality_adjustment(output_path, pil_format, target_size_bytes, quiet)
170
+ # Select and execute resizing strategy
171
+ result = _select_resizing_strategy(
172
+ img, pil_format, target_size_bytes, output_path, orig_width, orig_height, min_dimension, quiet
173
+ )
174
+
175
+ # Adjust final size if needed
176
+ _adjust_final_size(result, target_size_bytes, pil_format, exact_size, quiet)
137
177
 
138
178
  # Final report if not in quiet mode
139
179
  if not quiet:
140
- final_img: Image.Image = Image.open(output_path)
180
+ final_img: Image.Image = Image.open(result)
141
181
  final_width: int
142
182
  final_height: int
143
183
  final_width, final_height = final_img.size
144
- final_size: int = os.path.getsize(output_path)
184
+ final_size: int = os.path.getsize(result)
145
185
 
146
186
  print_comparison_table(
147
187
  orig_size,
@@ -155,38 +195,30 @@ def resize_to_target_filesize(
155
195
  print_result("Time taken", f"{elapsed:.2f} seconds")
156
196
  print_result(
157
197
  "Output file",
158
- f"{Colors.UNDERLINE}{os.path.basename(output_path)}{Colors.ENDC}",
198
+ f"{Colors.UNDERLINE}{os.path.basename(result)}{Colors.ENDC}",
159
199
  )
160
200
 
161
- return output_path
201
+ return result
162
202
 
163
203
 
164
- def _try_quality_adjustment(
204
+ def _binary_search_quality(
165
205
  img: Image.Image,
166
206
  pil_format: str,
167
207
  target_size_bytes: int,
168
- output_path: str,
169
- quiet: bool = False,
170
- ) -> Optional[str]:
171
- """Try to reach target size by adjusting quality only."""
172
- if not quiet:
173
- print("Trying quality adjustment without resizing...")
174
-
175
- # Start with wider quality range (1-100 instead of 1-95)
208
+ max_iterations: int,
209
+ quiet: bool = False
210
+ ) -> Tuple[Optional[int], Optional[int], Optional[io.BytesIO]]:
211
+ """Binary search for best quality setting."""
176
212
  low: int = 1
177
213
  high: int = 100
178
214
  best_quality: Optional[int] = None
179
215
  best_size: Optional[int] = None
180
216
  best_buffer: Optional[io.BytesIO] = None
181
217
  iteration: int = 0
182
- max_iterations: int = 12 # Increased from 10 for more precision
183
218
 
184
- # Binary search for best quality
185
219
  while low <= high and iteration < max_iterations:
186
220
  iteration += 1
187
221
  mid: int = (low + high) // 2
188
- size: int
189
- buffer: io.BytesIO
190
222
  size, buffer = get_file_size_bytes(img, pil_format, mid)
191
223
 
192
224
  if not quiet:
@@ -197,20 +229,36 @@ def _try_quality_adjustment(
197
229
  suffix=f"Size: {format_filesize(size)}",
198
230
  )
199
231
 
200
- # Update best if this is closest to target without going over
201
232
  if size <= target_size_bytes:
202
233
  if best_size is None or size > best_size:
203
234
  best_quality = mid
204
235
  best_size = size
205
236
  best_buffer = buffer
206
- low = mid + 1 # Try higher quality
237
+ low = mid + 1
207
238
  else:
208
- high = mid - 1 # Try lower quality
239
+ high = mid - 1
209
240
 
210
- # Add small delay for visual effect in progress bar if not in quiet mode
211
241
  if not quiet:
212
242
  time.sleep(0.01)
213
243
 
244
+ return best_quality, best_size, best_buffer
245
+
246
+
247
+ def _try_quality_adjustment(
248
+ img: Image.Image,
249
+ pil_format: str,
250
+ target_size_bytes: int,
251
+ output_path: str,
252
+ quiet: bool = False,
253
+ ) -> Optional[str]:
254
+ """Try to reach target size by adjusting quality only."""
255
+ if not quiet:
256
+ print("Trying quality adjustment without resizing...")
257
+
258
+ best_quality, best_size, best_buffer = _binary_search_quality(
259
+ img, pil_format, target_size_bytes, 12, quiet
260
+ )
261
+
214
262
  if best_size is not None and best_buffer is not None:
215
263
  if not quiet:
216
264
  print(
@@ -218,7 +266,6 @@ def _try_quality_adjustment(
218
266
  f"(size: {format_filesize(best_size)}){Colors.ENDC}"
219
267
  )
220
268
 
221
- # Write the buffer to file
222
269
  with open(output_path, "wb") as f:
223
270
  f.write(best_buffer.getvalue())
224
271
 
@@ -227,6 +274,45 @@ def _try_quality_adjustment(
227
274
  return None
228
275
 
229
276
 
277
+ def _try_scale_with_quality(
278
+ img: Image.Image,
279
+ pil_format: str,
280
+ target_size_bytes: int,
281
+ scale: float,
282
+ orig_width: int,
283
+ orig_height: int,
284
+ min_dimension: Optional[int],
285
+ quiet: bool = False
286
+ ) -> Tuple[Optional[int], Optional[io.BytesIO], Optional[float]]:
287
+ """Try a specific scale factor with quality adjustment."""
288
+ new_width: int = int(orig_width * scale)
289
+ new_height: int = int(orig_height * scale)
290
+
291
+ if min_dimension is not None:
292
+ if new_width < min_dimension or new_height < min_dimension:
293
+ scale_w: float = (min_dimension / new_width if new_width < min_dimension else 1)
294
+ scale_h: float = (min_dimension / new_height if new_height < min_dimension else 1)
295
+ scale = max(scale_w, scale_h)
296
+ new_width = int(orig_width * scale)
297
+ new_height = int(orig_height * scale)
298
+
299
+ if not quiet:
300
+ print(f"Trying scale factor {scale:.2f} ({new_width}×{new_height})...")
301
+
302
+ if new_width > 10000 or new_height > 10000:
303
+ return None, None, None
304
+
305
+ resized_img: Image.Image = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
306
+ size, buffer = _find_best_quality(resized_img, pil_format, target_size_bytes, quiet)
307
+
308
+ return size, buffer, scale
309
+
310
+
311
+ def _get_scale_factors(target_size_bytes: int) -> list[float]:
312
+ """Get appropriate scale factors based on target size."""
313
+ return [0.1, 0.2, 0.3, 0.4, 0.5] if target_size_bytes < 5 * 1024 else [1.0, 1.25, 1.5, 2.0, 3.0]
314
+
315
+
230
316
  def _try_combined_approach(
231
317
  img: Image.Image,
232
318
  pil_format: str,
@@ -237,130 +323,77 @@ def _try_combined_approach(
237
323
  min_dimension: Optional[int],
238
324
  quiet: bool = False,
239
325
  ) -> str:
240
- """Try a combined approach of slight upscaling and quality adjustment."""
326
+ """Try combined scaling and quality approach."""
241
327
  if not quiet:
242
328
  print("Trying combined scaling and quality approach...")
243
329
 
244
- # Try a series of scale factors, starting from original size and going up
245
- # This helps when the image is too small to reach the target size with quality alone
246
- scale_factors: Final[list[float]] = [1.0, 1.25, 1.5, 2.0, 3.0]
247
-
248
330
  best_size: Optional[int] = None
249
331
  best_buffer: Optional[io.BytesIO] = None
250
332
  best_scale: Optional[float] = None
251
333
 
252
- for scale in scale_factors:
253
- new_width: int = int(orig_width * scale)
254
- new_height: int = int(orig_height * scale)
255
-
256
- # Apply minimum dimension constraint if specified
257
- if min_dimension is not None:
258
- if new_width < min_dimension or new_height < min_dimension:
259
- scale_w: float = (min_dimension / new_width if new_width < min_dimension else 1)
260
- scale_h: float = (min_dimension / new_height if new_height < min_dimension else 1)
261
- scale = max(scale_w, scale_h)
262
- new_width = int(orig_width * scale)
263
- new_height = int(orig_height * scale)
264
-
265
- if not quiet:
266
- print(f"Trying scale factor {scale:.2f} ({new_width}×{new_height})...")
267
-
268
- # Skip if dimensions are unreasonably large
269
- if new_width > 10000 or new_height > 10000:
270
- continue
271
-
272
- # Use LANCZOS for best quality
273
- resized_img: Image.Image = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
274
-
275
- # Try quality adjustment for this size
276
- low: int = 1
277
- high: int = 100
278
- best_size_for_scale: Optional[int] = None
279
- best_buffer_for_scale: Optional[io.BytesIO] = None
280
-
281
- # Binary search for quality
282
- for _ in range(10): # Limit iterations
283
- mid: int = (low + high) // 2
284
- size: int
285
- buffer: io.BytesIO
286
- size, buffer = get_file_size_bytes(resized_img, pil_format, mid)
287
-
288
- if not quiet:
289
- print_progress_bar(
290
- _ + 1,
291
- 10,
292
- prefix=f"Quality {mid:2d}",
293
- suffix=f"Size: {format_filesize(size)}",
294
- )
295
-
296
- # Found a valid size
297
- if size <= target_size_bytes:
298
- if best_size_for_scale is None or size > best_size_for_scale:
299
- best_size_for_scale = size
300
- best_buffer_for_scale = buffer
301
- low = mid + 1
302
- else:
303
- high = mid - 1
334
+ for scale in _get_scale_factors(target_size_bytes):
335
+ size, buffer, scale = _try_scale_with_quality(
336
+ img, pil_format, target_size_bytes, scale, orig_width, orig_height, min_dimension, quiet
337
+ )
304
338
 
305
- # Update overall best if this scale produced a better result
306
- if best_size_for_scale is not None:
307
- if best_size is None or abs(best_size_for_scale - target_size_bytes) < abs(best_size -
308
- target_size_bytes):
309
- best_size = best_size_for_scale
310
- best_buffer = best_buffer_for_scale
339
+ if size is not None and buffer is not None:
340
+ if best_size is None or abs(size - target_size_bytes) < abs(best_size - target_size_bytes):
341
+ best_size = size
342
+ best_buffer = buffer
311
343
  best_scale = scale
312
344
 
313
- # If we're within 95% of the target size, consider it good enough and stop
314
- if (best_size_for_scale is not None and best_size_for_scale >= target_size_bytes * 0.95):
315
- break
345
+ if size >= target_size_bytes * 0.95:
346
+ break
316
347
 
317
348
  if best_buffer is None:
318
- # Fall back to resizing if combined approach failed
319
- return _try_resizing(
320
- img,
321
- pil_format,
322
- target_size_bytes,
323
- output_path,
324
- orig_width,
325
- orig_height,
326
- min_dimension,
327
- quiet,
328
- )
349
+ return _try_minimum_size(img, pil_format, output_path, min_dimension, quiet)
329
350
 
330
- # Write the best result to file
331
351
  with open(output_path, "wb") as f:
332
352
  f.write(best_buffer.getvalue())
333
353
 
334
354
  if not quiet:
335
355
  print(
336
- f"\n{Colors.GREEN}✓ Combined approach success: scale={best_scale:.2f}, "
337
- f"size={format_filesize(best_size)}{Colors.ENDC}"
356
+ f"\n{Colors.GREEN}✓ Found optimal size: {format_filesize(best_size)} with scale "
357
+ f"{best_scale:.2f}{Colors.ENDC}"
338
358
  )
339
359
 
340
360
  return output_path
341
361
 
342
362
 
343
- def _try_resizing(
363
+ def _apply_min_dimension_constraint(new_width: int, new_height: int,
364
+ min_dimension: Optional[int]) -> Tuple[int, int, float]:
365
+ """Apply minimum dimension constraint and return new dimensions and scale."""
366
+ if min_dimension is None:
367
+ return new_width, new_height, 1.0
368
+
369
+ if new_width < min_dimension or new_height < min_dimension:
370
+ scale_w: float = (min_dimension / new_width if new_width < min_dimension else 1)
371
+ scale_h: float = (min_dimension / new_height if new_height < min_dimension else 1)
372
+ scale = max(scale_w, scale_h)
373
+ new_width = max(min_dimension, int(new_width * scale))
374
+ new_height = max(min_dimension, int(new_height * scale))
375
+ return new_width, new_height, scale
376
+
377
+ return new_width, new_height, 1.0
378
+
379
+
380
+ def _binary_search_scale(
344
381
  img: Image.Image,
345
382
  pil_format: str,
346
383
  target_size_bytes: int,
347
- output_path: str,
348
384
  orig_width: int,
349
385
  orig_height: int,
350
386
  min_dimension: Optional[int],
351
- quiet: bool = False,
352
- ) -> str:
353
- """Try to reach target size by resizing the image."""
354
- if not quiet:
355
- print("Performing size-based optimization...")
356
-
387
+ quiet: bool = False
388
+ ) -> Tuple[Optional[int], Optional[io.BytesIO], Optional[float]]:
389
+ """Binary search for the best scale factor."""
357
390
  low_scale: float = 0.01
358
391
  high_scale: float = 1.0
359
392
  best_size: Optional[int] = None
360
393
  best_buffer: Optional[io.BytesIO] = None
361
394
  best_scale: Optional[float] = None
362
395
  iterations: int = 0
363
- max_iterations: int = 12 # Limit iterations for binary search
396
+ max_iterations: int = 12
364
397
 
365
398
  while high_scale - low_scale > 0.005 and iterations < max_iterations:
366
399
  iterations += 1
@@ -368,73 +401,81 @@ def _try_resizing(
368
401
  new_width: int = max(1, int(orig_width * mid_scale))
369
402
  new_height: int = max(1, int(orig_height * mid_scale))
370
403
 
371
- # Apply minimum dimension constraint if specified
372
- if min_dimension is not None:
373
- if new_width < min_dimension or new_height < min_dimension:
374
- scale_w: float = (min_dimension / new_width if new_width < min_dimension else 1)
375
- scale_h: float = (min_dimension / new_height if new_height < min_dimension else 1)
376
- scale = max(scale_w, scale_h)
377
- new_width = max(min_dimension, int(new_width * scale))
378
- new_height = max(min_dimension, int(new_height * scale))
404
+ new_width, new_height, _ = _apply_min_dimension_constraint(new_width, new_height, min_dimension)
379
405
 
380
406
  if not quiet:
381
407
  print_processing_step(iterations, f"Trying scale {mid_scale:.2f} ({new_width}×{new_height})")
382
408
 
383
- # Use LANCZOS for best quality
384
409
  resized_img: Image.Image = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
385
-
386
- # Try to find best quality for this size
387
- size: int
388
- buffer: io.BytesIO
389
410
  size, buffer = _find_best_quality(resized_img, pil_format, target_size_bytes, quiet)
390
411
 
391
- # Update best if this is closest to target without going over
392
412
  if size <= target_size_bytes:
393
413
  if best_size is None or size > best_size:
394
414
  best_size = size
395
415
  best_buffer = buffer
396
416
  best_scale = mid_scale
397
- low_scale = mid_scale # Try larger sizes
417
+ low_scale = mid_scale
398
418
  else:
399
- high_scale = mid_scale # Try smaller sizes
419
+ high_scale = mid_scale
400
420
 
401
- # Add small delay for visual effect in progress bar if not in quiet mode
402
421
  if not quiet:
403
422
  time.sleep(0.01)
404
423
 
405
- if best_buffer is None:
406
- # Last resort: use the smallest possible size with lowest quality
407
- smallest_width: int = 1 if min_dimension is None else min_dimension
408
- smallest_height: int = 1 if min_dimension is None else min_dimension
409
- tiny_img: Image.Image = img.resize((smallest_width, smallest_height), Image.Resampling.LANCZOS)
424
+ return best_size, best_buffer, best_scale
410
425
 
411
- min_quality: int = 1 # Lowest possible quality
412
- size: int
413
- buffer: io.BytesIO
414
- size, buffer = get_file_size_bytes(tiny_img, pil_format, min_quality)
415
426
 
416
- # Write this as our best attempt
417
- with open(output_path, "wb") as f:
418
- f.write(buffer.getvalue())
427
+ def _try_minimum_size(
428
+ img: Image.Image,
429
+ pil_format: str,
430
+ output_path: str,
431
+ min_dimension: Optional[int],
432
+ quiet: bool = False
433
+ ) -> str:
434
+ """Try the smallest possible size with lowest quality as last resort."""
435
+ smallest_width: int = 1 if min_dimension is None else min_dimension
436
+ smallest_height: int = 1 if min_dimension is None else min_dimension
437
+ tiny_img: Image.Image = img.resize((smallest_width, smallest_height), Image.Resampling.LANCZOS)
419
438
 
420
- if not quiet:
421
- print(
422
- f"\n{Colors.YELLOW}⚠ Could not reach target size. Using minimum size and quality."
423
- f"{Colors.ENDC}"
424
- )
439
+ _size, buffer = get_file_size_bytes(tiny_img, pil_format, 1)
425
440
 
426
- return output_path
441
+ with open(output_path, "wb") as f:
442
+ f.write(buffer.getvalue())
443
+
444
+ if not quiet:
445
+ print(
446
+ f"\n{Colors.YELLOW}⚠ Could not reach target size. Using minimum size and quality."
447
+ f"{Colors.ENDC}"
448
+ )
449
+
450
+ return output_path
451
+
452
+
453
+ def _try_resizing(
454
+ img: Image.Image,
455
+ pil_format: str,
456
+ target_size_bytes: int,
457
+ output_path: str,
458
+ orig_width: int,
459
+ orig_height: int,
460
+ min_dimension: Optional[int],
461
+ quiet: bool = False,
462
+ ) -> str:
463
+ """Try to reach target size by resizing the image."""
464
+ if not quiet:
465
+ print("Performing size-based optimization...")
466
+
467
+ best_size, best_buffer, best_scale = _binary_search_scale(
468
+ img, pil_format, target_size_bytes, orig_width, orig_height, min_dimension, quiet
469
+ )
470
+
471
+ if best_buffer is None:
472
+ return _try_minimum_size(img, pil_format, output_path, min_dimension, quiet)
427
473
 
428
- # Write the best result to file
429
474
  with open(output_path, "wb") as f:
430
475
  f.write(best_buffer.getvalue())
431
476
 
432
477
  if not quiet:
433
- if best_size is not None:
434
- found_size: str = format_filesize(best_size)
435
- else:
436
- found_size: str = "Unknown"
437
-
478
+ found_size: str = format_filesize(best_size) if best_size is not None else "Unknown"
438
479
  print(
439
480
  f"\n{Colors.GREEN}✓ Found optimal size: {found_size} with scale "
440
481
  f"{best_scale:.2f}{Colors.ENDC}"
File without changes