imgbytesizer 0.2.2__tar.gz → 0.2.3__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.
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/PKG-INFO +16 -3
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/README.md +15 -2
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer/__init__.py +1 -1
- imgbytesizer-0.2.3/imgbytesizer/formatter.py +17 -0
- imgbytesizer-0.2.3/imgbytesizer/logger.py +128 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer/main.py +31 -14
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer/resizer.py +91 -67
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer/utils.py +8 -10
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/PKG-INFO +16 -3
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/pyproject.toml +1 -1
- imgbytesizer-0.2.3/tests/test_formatter.py +12 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/tests/test_logger.py +4 -4
- imgbytesizer-0.2.2/imgbytesizer/formatter.py +0 -18
- imgbytesizer-0.2.2/imgbytesizer/logger.py +0 -206
- imgbytesizer-0.2.2/tests/test_formatter.py +0 -16
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/LICENSE +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/SOURCES.txt +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/dependency_links.txt +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/entry_points.txt +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/requires.txt +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/top_level.txt +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/setup.cfg +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/tests/test_main.py +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/tests/test_resizer.py +0 -0
- {imgbytesizer-0.2.2 → imgbytesizer-0.2.3}/tests/test_utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: imgbytesizer
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: A CLI tool to resize images to a target file size.
|
|
5
5
|
Author-email: pyyupsk <contact@fasu.dev>
|
|
6
6
|
License: MIT License
|
|
@@ -61,7 +61,7 @@ imgbytesizer large_image.jpg 300KB --min-dimension 400
|
|
|
61
61
|
### Command-Line Options
|
|
62
62
|
|
|
63
63
|
```bash
|
|
64
|
-
usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [
|
|
64
|
+
usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [--debug] [-q] [-v] [image_path] [target_size]
|
|
65
65
|
|
|
66
66
|
Resize an image to match a target file size
|
|
67
67
|
|
|
@@ -71,15 +71,28 @@ positional arguments:
|
|
|
71
71
|
|
|
72
72
|
options:
|
|
73
73
|
-h, --help show this help message and exit
|
|
74
|
+
-v, --version Show version information
|
|
75
|
+
|
|
76
|
+
primary options:
|
|
74
77
|
-o, --output OUTPUT Output path (default: input_resized.ext)
|
|
75
78
|
-f, --format {jpg,jpeg,png,webp}
|
|
76
79
|
Output format
|
|
80
|
+
|
|
81
|
+
advanced options:
|
|
77
82
|
--min-dimension MIN_DIMENSION
|
|
78
83
|
Minimum width/height in pixels
|
|
79
84
|
--no-exact Do not pad file to get exact target size
|
|
80
|
-
|
|
85
|
+
|
|
86
|
+
utility:
|
|
81
87
|
--debug Enable debug logging
|
|
82
88
|
-q, --quiet Minimal output
|
|
89
|
+
|
|
90
|
+
examples:
|
|
91
|
+
imgbytesizer image.jpg 500KB # Resize to 500 KB
|
|
92
|
+
imgbytesizer photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
|
|
93
|
+
imgbytesizer image.jpg 100KB -f webp # Resize and convert to WebP
|
|
94
|
+
imgbytesizer large.jpg 50KB --min-dimension 200 # Ensure min dimension is 200px
|
|
95
|
+
imgbytesizer -v # Show version information
|
|
83
96
|
```
|
|
84
97
|
|
|
85
98
|
## How It Works
|
|
@@ -47,7 +47,7 @@ imgbytesizer large_image.jpg 300KB --min-dimension 400
|
|
|
47
47
|
### Command-Line Options
|
|
48
48
|
|
|
49
49
|
```bash
|
|
50
|
-
usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [
|
|
50
|
+
usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [--debug] [-q] [-v] [image_path] [target_size]
|
|
51
51
|
|
|
52
52
|
Resize an image to match a target file size
|
|
53
53
|
|
|
@@ -57,15 +57,28 @@ positional arguments:
|
|
|
57
57
|
|
|
58
58
|
options:
|
|
59
59
|
-h, --help show this help message and exit
|
|
60
|
+
-v, --version Show version information
|
|
61
|
+
|
|
62
|
+
primary options:
|
|
60
63
|
-o, --output OUTPUT Output path (default: input_resized.ext)
|
|
61
64
|
-f, --format {jpg,jpeg,png,webp}
|
|
62
65
|
Output format
|
|
66
|
+
|
|
67
|
+
advanced options:
|
|
63
68
|
--min-dimension MIN_DIMENSION
|
|
64
69
|
Minimum width/height in pixels
|
|
65
70
|
--no-exact Do not pad file to get exact target size
|
|
66
|
-
|
|
71
|
+
|
|
72
|
+
utility:
|
|
67
73
|
--debug Enable debug logging
|
|
68
74
|
-q, --quiet Minimal output
|
|
75
|
+
|
|
76
|
+
examples:
|
|
77
|
+
imgbytesizer image.jpg 500KB # Resize to 500 KB
|
|
78
|
+
imgbytesizer photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
|
|
79
|
+
imgbytesizer image.jpg 100KB -f webp # Resize and convert to WebP
|
|
80
|
+
imgbytesizer large.jpg 50KB --min-dimension 200 # Ensure min dimension is 200px
|
|
81
|
+
imgbytesizer -v # Show version information
|
|
69
82
|
```
|
|
70
83
|
|
|
71
84
|
## How It Works
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Terminal formatting utilities for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def format_filesize(size_bytes: Union[int, float, None]) -> str:
|
|
9
|
+
"""Format file size in bytes to human-readable string."""
|
|
10
|
+
if size_bytes is None:
|
|
11
|
+
return "N/A"
|
|
12
|
+
size: float = float(size_bytes)
|
|
13
|
+
for unit in ["B", "KB", "MB", "GB"]:
|
|
14
|
+
if size < 1024:
|
|
15
|
+
return f"{size:.1f}{unit}"
|
|
16
|
+
size /= 1024
|
|
17
|
+
return f"{size:.1f}TB"
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Logging utilities for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Final, Optional, Tuple, TextIO
|
|
7
|
+
|
|
8
|
+
from .formatter import format_filesize
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# ANSI Color Codes for beautiful terminal output
|
|
12
|
+
class Colors:
|
|
13
|
+
RED: Final[str] = "\033[91m"
|
|
14
|
+
GREEN: Final[str] = "\033[92m"
|
|
15
|
+
YELLOW: Final[str] = "\033[93m"
|
|
16
|
+
ENDC: Final[str] = "\033[0m"
|
|
17
|
+
UNDERLINE: Final[str] = "\033[4m"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def setup_logger() -> logging.Logger:
|
|
21
|
+
"""Set up and configure the logger."""
|
|
22
|
+
logger: logging.Logger = logging.getLogger("imgbytesizer")
|
|
23
|
+
logger.setLevel(logging.INFO)
|
|
24
|
+
|
|
25
|
+
# Create console handler
|
|
26
|
+
handler: logging.StreamHandler[TextIO] = logging.StreamHandler() # type: ignore
|
|
27
|
+
handler.setLevel(logging.INFO)
|
|
28
|
+
|
|
29
|
+
# Create formatter
|
|
30
|
+
formatter: logging.Formatter = logging.Formatter(
|
|
31
|
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
32
|
+
)
|
|
33
|
+
handler.setFormatter(formatter)
|
|
34
|
+
|
|
35
|
+
# Add handler to logger
|
|
36
|
+
logger.addHandler(handler)
|
|
37
|
+
|
|
38
|
+
return logger
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def print_result(label: str, value: str, status: Optional[str] = None) -> None:
|
|
42
|
+
"""Print a name-value pair with optional status color."""
|
|
43
|
+
if status == "good":
|
|
44
|
+
value = f"{Colors.GREEN}{value}{Colors.ENDC}"
|
|
45
|
+
elif status == "bad":
|
|
46
|
+
value = f"{Colors.RED}{value}{Colors.ENDC}"
|
|
47
|
+
elif status == "warning":
|
|
48
|
+
value = f"{Colors.YELLOW}{value}{Colors.ENDC}"
|
|
49
|
+
|
|
50
|
+
print(f"{label:12} {value}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def print_comparison_table(
|
|
54
|
+
orig_size: int,
|
|
55
|
+
orig_dimensions: Tuple[int, int],
|
|
56
|
+
final_size: int,
|
|
57
|
+
final_dimensions: Tuple[int, int],
|
|
58
|
+
target_size: int,
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Print a comparison table of original and final image properties."""
|
|
61
|
+
print("\nComparison:")
|
|
62
|
+
print("-" * 40)
|
|
63
|
+
|
|
64
|
+
# Original dimensions
|
|
65
|
+
orig_width, orig_height = orig_dimensions
|
|
66
|
+
print_result("Original", f"{orig_width} × {orig_height} pixels")
|
|
67
|
+
print_result("Size", format_filesize(orig_size))
|
|
68
|
+
|
|
69
|
+
# Final dimensions
|
|
70
|
+
final_width, final_height = final_dimensions
|
|
71
|
+
print_result("Final", f"{final_width} × {final_height} pixels")
|
|
72
|
+
print_result("Size", format_filesize(final_size))
|
|
73
|
+
|
|
74
|
+
# Target size
|
|
75
|
+
print_result("Target", format_filesize(target_size))
|
|
76
|
+
|
|
77
|
+
# Calculate and print differences
|
|
78
|
+
size_diff: int = final_size - orig_size
|
|
79
|
+
size_diff_percent: float = (size_diff / orig_size) * 100
|
|
80
|
+
size_status: str = "good" if size_diff <= 0 else "bad"
|
|
81
|
+
|
|
82
|
+
print_result(
|
|
83
|
+
"Size change",
|
|
84
|
+
f"{format_filesize(size_diff)} ({size_diff_percent:+.1f}%)",
|
|
85
|
+
size_status,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# Dimension changes
|
|
89
|
+
width_diff: int = final_width - orig_width
|
|
90
|
+
height_diff: int = final_height - orig_height
|
|
91
|
+
width_diff_percent: float = (width_diff / orig_width) * 100
|
|
92
|
+
height_diff_percent: float = (height_diff / orig_height) * 100
|
|
93
|
+
|
|
94
|
+
print_result(
|
|
95
|
+
"Width change",
|
|
96
|
+
f"{width_diff:+d} pixels ({width_diff_percent:+.1f}%)",
|
|
97
|
+
"good" if width_diff <= 0 else "warning",
|
|
98
|
+
)
|
|
99
|
+
print_result(
|
|
100
|
+
"Height change",
|
|
101
|
+
f"{height_diff:+d} pixels ({height_diff_percent:+.1f}%)",
|
|
102
|
+
"good" if height_diff <= 0 else "warning",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
print("-" * 40)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def print_processing_step(step: int, message: str) -> None:
|
|
109
|
+
"""Print a processing step with step number."""
|
|
110
|
+
print(f"\n[{step}] {message}")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def print_progress_bar(
|
|
114
|
+
iteration: int,
|
|
115
|
+
total: int,
|
|
116
|
+
prefix: str = "",
|
|
117
|
+
suffix: str = "",
|
|
118
|
+
decimals: int = 1,
|
|
119
|
+
length: int = 50,
|
|
120
|
+
fill: str = "█",
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Print a progress bar."""
|
|
123
|
+
percent: str = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
|
|
124
|
+
filled_length: int = int(length * iteration // total)
|
|
125
|
+
bar: str = fill * filled_length + "-" * (length - filled_length)
|
|
126
|
+
print(f"\r{prefix} |{bar}| {percent}% {suffix}", end="\r")
|
|
127
|
+
if iteration == total:
|
|
128
|
+
print()
|
|
@@ -7,21 +7,27 @@ import logging
|
|
|
7
7
|
import sys
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
|
|
10
|
+
from pyfiglet import Figlet
|
|
11
|
+
|
|
10
12
|
from .logger import setup_logger
|
|
11
13
|
from .resizer import resize_to_target_filesize
|
|
12
14
|
from .utils import IMG_FORMATS, parse_filesize
|
|
13
15
|
|
|
16
|
+
f: Figlet = Figlet(font='slant')
|
|
17
|
+
|
|
14
18
|
|
|
15
19
|
def main() -> int:
|
|
16
20
|
"""Main entry point for the CLI."""
|
|
17
21
|
# Setup logger
|
|
18
|
-
logger = setup_logger()
|
|
22
|
+
logger: logging.Logger = setup_logger()
|
|
23
|
+
|
|
24
|
+
print(f.renderText('ImgByteSizer'))
|
|
19
25
|
|
|
20
|
-
parser = argparse.ArgumentParser(
|
|
26
|
+
parser: argparse.ArgumentParser = argparse.ArgumentParser(
|
|
21
27
|
description="Resize an image to match a target file size",
|
|
22
28
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
23
29
|
epilog="""
|
|
24
|
-
|
|
30
|
+
examples:
|
|
25
31
|
%(prog)s image.jpg 500KB # Resize to 500 KB
|
|
26
32
|
%(prog)s photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
|
|
27
33
|
%(prog)s image.jpg 100KB -f webp # Resize and convert to WebP
|
|
@@ -30,22 +36,33 @@ Examples:
|
|
|
30
36
|
""",
|
|
31
37
|
)
|
|
32
38
|
|
|
39
|
+
# Version
|
|
40
|
+
parser.add_argument("-v", "--version", action="store_true", help="Show version information")
|
|
41
|
+
|
|
33
42
|
parser.add_argument("image_path", nargs="?", help="Path to the input image")
|
|
34
43
|
parser.add_argument("target_size", nargs="?", help='Target file size (e.g., "1MB", "500KB")')
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
44
|
+
|
|
45
|
+
# Primary options
|
|
46
|
+
primary: argparse._ArgumentGroup = parser.add_argument_group("primary options")
|
|
47
|
+
primary.add_argument("-o", "--output", help="Output path (default: input_resized.ext)")
|
|
48
|
+
primary.add_argument("-f", "--format", choices=IMG_FORMATS, help="Output format")
|
|
49
|
+
|
|
50
|
+
# Advanced options
|
|
51
|
+
advanced: argparse._ArgumentGroup = parser.add_argument_group("advanced options")
|
|
52
|
+
advanced.add_argument("--min-dimension", type=int, help="Minimum width/height in pixels")
|
|
53
|
+
advanced.add_argument(
|
|
39
54
|
"--no-exact",
|
|
40
55
|
action="store_true",
|
|
41
56
|
help="Do not pad file to get exact target size",
|
|
42
57
|
)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
parser.
|
|
58
|
+
|
|
59
|
+
# Utility and debug
|
|
60
|
+
utility = parser.add_argument_group("utility")
|
|
61
|
+
utility.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
62
|
+
utility.add_argument("-q", "--quiet", action="store_true", help="Minimal output")
|
|
46
63
|
|
|
47
64
|
# Handle version flag before checking required arguments
|
|
48
|
-
args = parser.parse_args()
|
|
65
|
+
args: argparse.Namespace = parser.parse_args()
|
|
49
66
|
|
|
50
67
|
# Handle version request
|
|
51
68
|
if args.version:
|
|
@@ -66,19 +83,19 @@ Examples:
|
|
|
66
83
|
return 0
|
|
67
84
|
|
|
68
85
|
# Validate input file exists
|
|
69
|
-
image_path = Path(args.image_path)
|
|
86
|
+
image_path: Path = Path(args.image_path)
|
|
70
87
|
if not image_path.exists():
|
|
71
88
|
logger.error(f"Input file not found: {args.image_path}")
|
|
72
89
|
return 1
|
|
73
90
|
|
|
74
91
|
try:
|
|
75
|
-
target_bytes = parse_filesize(args.target_size)
|
|
92
|
+
target_bytes: int = parse_filesize(args.target_size)
|
|
76
93
|
except ValueError as e:
|
|
77
94
|
logger.error(f"Error: {e}")
|
|
78
95
|
return 1
|
|
79
96
|
|
|
80
97
|
try:
|
|
81
|
-
output_path = resize_to_target_filesize(
|
|
98
|
+
output_path: str = resize_to_target_filesize(
|
|
82
99
|
args.image_path,
|
|
83
100
|
target_bytes,
|
|
84
101
|
args.output,
|
|
@@ -7,7 +7,7 @@ import logging
|
|
|
7
7
|
import os
|
|
8
8
|
import time
|
|
9
9
|
from pathlib import Path
|
|
10
|
-
from typing import Optional, Tuple, Union
|
|
10
|
+
from typing import Final, Optional, Tuple, Union
|
|
11
11
|
|
|
12
12
|
from PIL import Image, ImageFile
|
|
13
13
|
|
|
@@ -21,7 +21,7 @@ from .utils import get_file_size_bytes, get_output_format, get_output_path
|
|
|
21
21
|
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
|
22
22
|
|
|
23
23
|
# Get logger
|
|
24
|
-
logger = logging.getLogger("imgbytesizer")
|
|
24
|
+
logger: logging.Logger = logging.getLogger("imgbytesizer")
|
|
25
25
|
|
|
26
26
|
|
|
27
27
|
def resize_to_target_filesize(
|
|
@@ -34,7 +34,7 @@ def resize_to_target_filesize(
|
|
|
34
34
|
quiet: bool = False,
|
|
35
35
|
) -> str:
|
|
36
36
|
"""Resize an image to match a target file size in bytes."""
|
|
37
|
-
start_time = time.time()
|
|
37
|
+
start_time: float = time.time()
|
|
38
38
|
|
|
39
39
|
# Load the image and get original info
|
|
40
40
|
print_processing_step(
|
|
@@ -42,16 +42,18 @@ def resize_to_target_filesize(
|
|
|
42
42
|
)
|
|
43
43
|
|
|
44
44
|
try:
|
|
45
|
-
img = Image.open(image_path)
|
|
45
|
+
img: Image.Image = Image.open(image_path)
|
|
46
46
|
img.load() # Ensure image is fully loaded
|
|
47
47
|
except Exception as e:
|
|
48
48
|
logger.error(f"Could not open image: {e}")
|
|
49
49
|
raise
|
|
50
50
|
|
|
51
|
+
orig_width: int
|
|
52
|
+
orig_height: int
|
|
51
53
|
orig_width, orig_height = img.size
|
|
52
54
|
|
|
53
55
|
# Normalize format names and determine output path
|
|
54
|
-
pil_format = get_output_format(img.format or "JPEG", format_name)
|
|
56
|
+
pil_format: str = get_output_format(img.format or "JPEG", format_name)
|
|
55
57
|
output_path = get_output_path(image_path, output_path, pil_format)
|
|
56
58
|
|
|
57
59
|
# Print image information if not in quiet mode
|
|
@@ -60,12 +62,12 @@ def resize_to_target_filesize(
|
|
|
60
62
|
print_result("Format", pil_format)
|
|
61
63
|
print_result("Dimensions", f"{orig_width} × {orig_height} pixels")
|
|
62
64
|
|
|
63
|
-
orig_size = os.path.getsize(image_path)
|
|
65
|
+
orig_size: int = os.path.getsize(image_path)
|
|
64
66
|
print_result("Size", format_filesize(orig_size))
|
|
65
67
|
print_result("Target size", format_filesize(target_size_bytes))
|
|
66
68
|
else:
|
|
67
69
|
# Even in quiet mode, we need the original size
|
|
68
|
-
orig_size = os.path.getsize(image_path)
|
|
70
|
+
orig_size: int = os.path.getsize(image_path)
|
|
69
71
|
|
|
70
72
|
# Check if resizing is needed
|
|
71
73
|
if orig_size <= target_size_bytes:
|
|
@@ -92,7 +94,9 @@ def resize_to_target_filesize(
|
|
|
92
94
|
# For formats that support quality adjustment, try that first
|
|
93
95
|
if pil_format in ["JPEG", "WEBP"]:
|
|
94
96
|
# First, try quality adjustment with original dimensions
|
|
95
|
-
result = _try_quality_adjustment(
|
|
97
|
+
result: Optional[str] = _try_quality_adjustment(
|
|
98
|
+
img, pil_format, target_size_bytes, output_path, quiet
|
|
99
|
+
)
|
|
96
100
|
|
|
97
101
|
# If quality adjustment alone doesn't work (image too small),
|
|
98
102
|
# try combined approach with resizing
|
|
@@ -122,7 +126,7 @@ def resize_to_target_filesize(
|
|
|
122
126
|
|
|
123
127
|
# Fine-tuning to match exact target size if needed
|
|
124
128
|
if exact_size and os.path.exists(output_path):
|
|
125
|
-
current_size = os.path.getsize(output_path)
|
|
129
|
+
current_size: int = os.path.getsize(output_path)
|
|
126
130
|
if current_size < target_size_bytes:
|
|
127
131
|
_adjust_to_exact_size(output_path, target_size_bytes, quiet)
|
|
128
132
|
elif current_size > target_size_bytes and pil_format in ["JPEG", "WEBP"]:
|
|
@@ -133,9 +137,11 @@ def resize_to_target_filesize(
|
|
|
133
137
|
|
|
134
138
|
# Final report if not in quiet mode
|
|
135
139
|
if not quiet:
|
|
136
|
-
final_img = Image.open(output_path)
|
|
140
|
+
final_img: Image.Image = Image.open(output_path)
|
|
141
|
+
final_width: int
|
|
142
|
+
final_height: int
|
|
137
143
|
final_width, final_height = final_img.size
|
|
138
|
-
final_size = os.path.getsize(output_path)
|
|
144
|
+
final_size: int = os.path.getsize(output_path)
|
|
139
145
|
|
|
140
146
|
print_comparison_table(
|
|
141
147
|
orig_size,
|
|
@@ -145,7 +151,7 @@ def resize_to_target_filesize(
|
|
|
145
151
|
target_size_bytes,
|
|
146
152
|
)
|
|
147
153
|
|
|
148
|
-
elapsed = time.time() - start_time
|
|
154
|
+
elapsed: float = time.time() - start_time
|
|
149
155
|
print_result("Time taken", f"{elapsed:.2f} seconds")
|
|
150
156
|
print_result(
|
|
151
157
|
"Output file",
|
|
@@ -167,17 +173,20 @@ def _try_quality_adjustment(
|
|
|
167
173
|
print("Trying quality adjustment without resizing...")
|
|
168
174
|
|
|
169
175
|
# Start with wider quality range (1-100 instead of 1-95)
|
|
170
|
-
low
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
+
low: int = 1
|
|
177
|
+
high: int = 100
|
|
178
|
+
best_quality: Optional[int] = None
|
|
179
|
+
best_size: Optional[int] = None
|
|
180
|
+
best_buffer: Optional[io.BytesIO] = None
|
|
181
|
+
iteration: int = 0
|
|
182
|
+
max_iterations: int = 12 # Increased from 10 for more precision
|
|
176
183
|
|
|
177
184
|
# Binary search for best quality
|
|
178
185
|
while low <= high and iteration < max_iterations:
|
|
179
186
|
iteration += 1
|
|
180
|
-
mid = (low + high) // 2
|
|
187
|
+
mid: int = (low + high) // 2
|
|
188
|
+
size: int
|
|
189
|
+
buffer: io.BytesIO
|
|
181
190
|
size, buffer = get_file_size_bytes(img, pil_format, mid)
|
|
182
191
|
|
|
183
192
|
if not quiet:
|
|
@@ -234,24 +243,24 @@ def _try_combined_approach(
|
|
|
234
243
|
|
|
235
244
|
# Try a series of scale factors, starting from original size and going up
|
|
236
245
|
# This helps when the image is too small to reach the target size with quality alone
|
|
237
|
-
scale_factors = [1.0, 1.25, 1.5, 2.0, 3.0]
|
|
246
|
+
scale_factors: Final[list[float]] = [1.0, 1.25, 1.5, 2.0, 3.0]
|
|
238
247
|
|
|
239
|
-
best_size = None
|
|
240
|
-
best_buffer = None
|
|
241
|
-
best_scale = None
|
|
248
|
+
best_size: Optional[int] = None
|
|
249
|
+
best_buffer: Optional[io.BytesIO] = None
|
|
250
|
+
best_scale: Optional[float] = None
|
|
242
251
|
|
|
243
252
|
for scale in scale_factors:
|
|
244
|
-
new_width = int(orig_width * scale)
|
|
245
|
-
new_height = int(orig_height * scale)
|
|
253
|
+
new_width: int = int(orig_width * scale)
|
|
254
|
+
new_height: int = int(orig_height * scale)
|
|
246
255
|
|
|
247
256
|
# Apply minimum dimension constraint if specified
|
|
248
257
|
if min_dimension is not None:
|
|
249
258
|
if new_width < min_dimension or new_height < min_dimension:
|
|
250
|
-
scale_w = min_dimension / new_width if new_width < min_dimension else 1
|
|
251
|
-
scale_h =
|
|
252
|
-
|
|
253
|
-
new_width =
|
|
254
|
-
new_height =
|
|
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)
|
|
255
264
|
|
|
256
265
|
if not quiet:
|
|
257
266
|
print(f"Trying scale factor {scale:.2f} ({new_width}×{new_height})...")
|
|
@@ -261,16 +270,19 @@ def _try_combined_approach(
|
|
|
261
270
|
continue
|
|
262
271
|
|
|
263
272
|
# Use LANCZOS for best quality
|
|
264
|
-
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
273
|
+
resized_img: Image.Image = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
265
274
|
|
|
266
275
|
# Try quality adjustment for this size
|
|
267
|
-
low
|
|
268
|
-
|
|
269
|
-
|
|
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
|
|
270
280
|
|
|
271
281
|
# Binary search for quality
|
|
272
282
|
for _ in range(10): # Limit iterations
|
|
273
|
-
mid = (low + high) // 2
|
|
283
|
+
mid: int = (low + high) // 2
|
|
284
|
+
size: int
|
|
285
|
+
buffer: io.BytesIO
|
|
274
286
|
size, buffer = get_file_size_bytes(resized_img, pil_format, mid)
|
|
275
287
|
|
|
276
288
|
if not quiet:
|
|
@@ -342,25 +354,25 @@ def _try_resizing(
|
|
|
342
354
|
if not quiet:
|
|
343
355
|
print("Performing size-based optimization...")
|
|
344
356
|
|
|
345
|
-
low_scale = 0.01
|
|
346
|
-
high_scale = 1.0
|
|
347
|
-
best_size = None
|
|
348
|
-
best_buffer = None
|
|
349
|
-
best_scale = None
|
|
350
|
-
iterations = 0
|
|
351
|
-
max_iterations = 12 # Limit iterations for binary search
|
|
357
|
+
low_scale: float = 0.01
|
|
358
|
+
high_scale: float = 1.0
|
|
359
|
+
best_size: Optional[int] = None
|
|
360
|
+
best_buffer: Optional[io.BytesIO] = None
|
|
361
|
+
best_scale: Optional[float] = None
|
|
362
|
+
iterations: int = 0
|
|
363
|
+
max_iterations: int = 12 # Limit iterations for binary search
|
|
352
364
|
|
|
353
365
|
while high_scale - low_scale > 0.005 and iterations < max_iterations:
|
|
354
366
|
iterations += 1
|
|
355
|
-
mid_scale = (low_scale + high_scale) / 2
|
|
356
|
-
new_width = max(1, int(orig_width * mid_scale))
|
|
357
|
-
new_height = max(1, int(orig_height * mid_scale))
|
|
367
|
+
mid_scale: float = (low_scale + high_scale) / 2
|
|
368
|
+
new_width: int = max(1, int(orig_width * mid_scale))
|
|
369
|
+
new_height: int = max(1, int(orig_height * mid_scale))
|
|
358
370
|
|
|
359
371
|
# Apply minimum dimension constraint if specified
|
|
360
372
|
if min_dimension is not None:
|
|
361
373
|
if new_width < min_dimension or new_height < min_dimension:
|
|
362
|
-
scale_w = min_dimension / new_width if new_width < min_dimension else 1
|
|
363
|
-
scale_h =
|
|
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
|
|
364
376
|
scale = max(scale_w, scale_h)
|
|
365
377
|
new_width = max(min_dimension, int(new_width * scale))
|
|
366
378
|
new_height = max(min_dimension, int(new_height * scale))
|
|
@@ -369,9 +381,11 @@ def _try_resizing(
|
|
|
369
381
|
print_processing_step(iterations, f"Trying scale {mid_scale:.2f} ({new_width}×{new_height})")
|
|
370
382
|
|
|
371
383
|
# Use LANCZOS for best quality
|
|
372
|
-
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
384
|
+
resized_img: Image.Image = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
373
385
|
|
|
374
386
|
# Try to find best quality for this size
|
|
387
|
+
size: int
|
|
388
|
+
buffer: io.BytesIO
|
|
375
389
|
size, buffer = _find_best_quality(resized_img, pil_format, target_size_bytes, quiet)
|
|
376
390
|
|
|
377
391
|
# Update best if this is closest to target without going over
|
|
@@ -390,11 +404,13 @@ def _try_resizing(
|
|
|
390
404
|
|
|
391
405
|
if best_buffer is None:
|
|
392
406
|
# Last resort: use the smallest possible size with lowest quality
|
|
393
|
-
smallest_width = 1 if min_dimension is None else min_dimension
|
|
394
|
-
smallest_height = 1 if min_dimension is None else min_dimension
|
|
395
|
-
tiny_img = img.resize((smallest_width, smallest_height), Image.Resampling.LANCZOS)
|
|
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)
|
|
396
410
|
|
|
397
|
-
min_quality = 1 # Lowest possible quality
|
|
411
|
+
min_quality: int = 1 # Lowest possible quality
|
|
412
|
+
size: int
|
|
413
|
+
buffer: io.BytesIO
|
|
398
414
|
size, buffer = get_file_size_bytes(tiny_img, pil_format, min_quality)
|
|
399
415
|
|
|
400
416
|
# Write this as our best attempt
|
|
@@ -415,9 +431,9 @@ def _try_resizing(
|
|
|
415
431
|
|
|
416
432
|
if not quiet:
|
|
417
433
|
if best_size is not None:
|
|
418
|
-
found_size = format_filesize(best_size)
|
|
434
|
+
found_size: str = format_filesize(best_size)
|
|
419
435
|
else:
|
|
420
|
-
found_size = "Unknown"
|
|
436
|
+
found_size: str = "Unknown"
|
|
421
437
|
|
|
422
438
|
print(
|
|
423
439
|
f"\n{Colors.GREEN}✓ Found optimal size: {found_size} with scale "
|
|
@@ -434,15 +450,18 @@ def _find_best_quality(
|
|
|
434
450
|
quiet: bool = False
|
|
435
451
|
) -> Tuple[int, io.BytesIO]:
|
|
436
452
|
"""Find the best quality setting for a given image size."""
|
|
437
|
-
low
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
453
|
+
low: int = 1
|
|
454
|
+
high: int = 100 # Extended to 100 from 95
|
|
455
|
+
best_size: Optional[int] = None
|
|
456
|
+
best_buffer: Optional[io.BytesIO] = None
|
|
457
|
+
iteration: int = 0
|
|
458
|
+
max_iterations: int = 12 # Increased from 10
|
|
442
459
|
|
|
443
460
|
while low <= high and iteration < max_iterations:
|
|
444
461
|
iteration += 1
|
|
445
|
-
mid = (low + high) // 2
|
|
462
|
+
mid: int = (low + high) // 2
|
|
463
|
+
size: int
|
|
464
|
+
buffer: io.BytesIO
|
|
446
465
|
size, buffer = get_file_size_bytes(img, pil_format, mid)
|
|
447
466
|
|
|
448
467
|
if not quiet:
|
|
@@ -468,6 +487,8 @@ def _find_best_quality(
|
|
|
468
487
|
|
|
469
488
|
if best_buffer is None:
|
|
470
489
|
# If all qualities exceed target, use lowest quality
|
|
490
|
+
size: int
|
|
491
|
+
buffer: io.BytesIO
|
|
471
492
|
size, buffer = get_file_size_bytes(img, pil_format, 1)
|
|
472
493
|
return size, buffer
|
|
473
494
|
|
|
@@ -483,20 +504,23 @@ def _final_quality_adjustment(
|
|
|
483
504
|
) -> None:
|
|
484
505
|
"""Make a final quality adjustment to get closer to target size."""
|
|
485
506
|
try:
|
|
486
|
-
img = Image.open(image_path)
|
|
507
|
+
img: Image.Image = Image.open(image_path)
|
|
487
508
|
|
|
488
509
|
# Get current size
|
|
489
|
-
current_size = os.path.getsize(image_path)
|
|
510
|
+
current_size: int = os.path.getsize(image_path)
|
|
490
511
|
|
|
491
512
|
if current_size <= target_size_bytes:
|
|
492
513
|
return
|
|
493
514
|
|
|
494
515
|
# Try to reduce quality to get closer to target
|
|
495
|
-
low
|
|
496
|
-
|
|
516
|
+
low: int = 1
|
|
517
|
+
high: int = 100
|
|
518
|
+
best_buffer: Optional[io.BytesIO] = None
|
|
497
519
|
|
|
498
520
|
for _ in range(8): # Limit iterations for speed
|
|
499
|
-
mid = (low + high) // 2
|
|
521
|
+
mid: int = (low + high) // 2
|
|
522
|
+
size: int
|
|
523
|
+
buffer: io.BytesIO
|
|
500
524
|
size, buffer = get_file_size_bytes(img, pil_format, mid)
|
|
501
525
|
|
|
502
526
|
if size <= target_size_bytes:
|
|
@@ -519,10 +543,10 @@ def _adjust_to_exact_size(output_path: str, target_size_bytes: int, quiet: bool
|
|
|
519
543
|
print("Adjusting to exact target size...")
|
|
520
544
|
|
|
521
545
|
# Read the current image
|
|
522
|
-
current_size = os.path.getsize(output_path)
|
|
546
|
+
current_size: int = os.path.getsize(output_path)
|
|
523
547
|
|
|
524
548
|
# Calculate padding needed
|
|
525
|
-
padding_needed = max(0, target_size_bytes - current_size)
|
|
549
|
+
padding_needed: int = max(0, target_size_bytes - current_size)
|
|
526
550
|
if padding_needed <= 0:
|
|
527
551
|
return
|
|
528
552
|
|
|
@@ -5,15 +5,15 @@ Utility functions for imgbytesizer.
|
|
|
5
5
|
import io
|
|
6
6
|
import logging
|
|
7
7
|
from pathlib import Path
|
|
8
|
-
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
8
|
+
from typing import Any, Dict, Final, List, Optional, Tuple, Union
|
|
9
9
|
|
|
10
10
|
from PIL import Image
|
|
11
11
|
|
|
12
12
|
# Supported image formats
|
|
13
|
-
IMG_FORMATS: List[str] = ["jpg", "jpeg", "png", "webp"]
|
|
13
|
+
IMG_FORMATS: Final[List[str]] = ["jpg", "jpeg", "png", "webp"]
|
|
14
14
|
|
|
15
15
|
# Logger
|
|
16
|
-
logger = logging.getLogger("imgbytesizer")
|
|
16
|
+
logger: logging.Logger = logging.getLogger("imgbytesizer")
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
def parse_filesize(size_str: str) -> int:
|
|
@@ -43,7 +43,7 @@ def get_file_size_bytes(img: Image.Image,
|
|
|
43
43
|
format_name: str,
|
|
44
44
|
quality: Optional[int] = None) -> Tuple[int, io.BytesIO]:
|
|
45
45
|
"""Get the file size in bytes for an image with the specified format and quality."""
|
|
46
|
-
out_buffer = io.BytesIO()
|
|
46
|
+
out_buffer: io.BytesIO = io.BytesIO()
|
|
47
47
|
save_args: Dict[str, Any] = {"format": format_name}
|
|
48
48
|
|
|
49
49
|
# Apply quality settings based on format
|
|
@@ -62,7 +62,7 @@ def get_file_size_bytes(img: Image.Image,
|
|
|
62
62
|
|
|
63
63
|
try:
|
|
64
64
|
img.save(out_buffer, **save_args)
|
|
65
|
-
size = out_buffer.tell()
|
|
65
|
+
size: int = out_buffer.tell()
|
|
66
66
|
logger.debug(f"Image size with {format_name}, quality {quality}: {size} bytes")
|
|
67
67
|
return size, out_buffer
|
|
68
68
|
except Exception as e:
|
|
@@ -72,10 +72,7 @@ def get_file_size_bytes(img: Image.Image,
|
|
|
72
72
|
|
|
73
73
|
def get_output_format(input_format: str, requested_format: Optional[str] = None) -> str:
|
|
74
74
|
"""Determine the output format based on input and requested format."""
|
|
75
|
-
if requested_format
|
|
76
|
-
format_name = requested_format.upper()
|
|
77
|
-
else:
|
|
78
|
-
format_name = input_format
|
|
75
|
+
format_name: str = requested_format.upper() if requested_format else input_format
|
|
79
76
|
|
|
80
77
|
# Normalize format names
|
|
81
78
|
if format_name == "JPG":
|
|
@@ -90,12 +87,13 @@ def get_output_path(
|
|
|
90
87
|
format_name: Optional[str] = None,
|
|
91
88
|
) -> str:
|
|
92
89
|
"""Generate appropriate output path."""
|
|
93
|
-
path = Path(image_path)
|
|
90
|
+
path: Path = Path(image_path)
|
|
94
91
|
|
|
95
92
|
if output_path:
|
|
96
93
|
return output_path
|
|
97
94
|
|
|
98
95
|
# Determine extension
|
|
96
|
+
ext: str
|
|
99
97
|
if format_name:
|
|
100
98
|
ext = format_name.lower()
|
|
101
99
|
if ext == "jpeg":
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: imgbytesizer
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: A CLI tool to resize images to a target file size.
|
|
5
5
|
Author-email: pyyupsk <contact@fasu.dev>
|
|
6
6
|
License: MIT License
|
|
@@ -61,7 +61,7 @@ imgbytesizer large_image.jpg 300KB --min-dimension 400
|
|
|
61
61
|
### Command-Line Options
|
|
62
62
|
|
|
63
63
|
```bash
|
|
64
|
-
usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [
|
|
64
|
+
usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [--debug] [-q] [-v] [image_path] [target_size]
|
|
65
65
|
|
|
66
66
|
Resize an image to match a target file size
|
|
67
67
|
|
|
@@ -71,15 +71,28 @@ positional arguments:
|
|
|
71
71
|
|
|
72
72
|
options:
|
|
73
73
|
-h, --help show this help message and exit
|
|
74
|
+
-v, --version Show version information
|
|
75
|
+
|
|
76
|
+
primary options:
|
|
74
77
|
-o, --output OUTPUT Output path (default: input_resized.ext)
|
|
75
78
|
-f, --format {jpg,jpeg,png,webp}
|
|
76
79
|
Output format
|
|
80
|
+
|
|
81
|
+
advanced options:
|
|
77
82
|
--min-dimension MIN_DIMENSION
|
|
78
83
|
Minimum width/height in pixels
|
|
79
84
|
--no-exact Do not pad file to get exact target size
|
|
80
|
-
|
|
85
|
+
|
|
86
|
+
utility:
|
|
81
87
|
--debug Enable debug logging
|
|
82
88
|
-q, --quiet Minimal output
|
|
89
|
+
|
|
90
|
+
examples:
|
|
91
|
+
imgbytesizer image.jpg 500KB # Resize to 500 KB
|
|
92
|
+
imgbytesizer photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
|
|
93
|
+
imgbytesizer image.jpg 100KB -f webp # Resize and convert to WebP
|
|
94
|
+
imgbytesizer large.jpg 50KB --min-dimension 200 # Ensure min dimension is 200px
|
|
95
|
+
imgbytesizer -v # Show version information
|
|
83
96
|
```
|
|
84
97
|
|
|
85
98
|
## How It Works
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from imgbytesizer.formatter import format_filesize
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_format_filesize():
|
|
5
|
+
# Test various file sizes
|
|
6
|
+
assert format_filesize(500) == "500.0B"
|
|
7
|
+
assert format_filesize(1024) == "1.0KB"
|
|
8
|
+
assert format_filesize(1024 * 1024) == "1.0MB"
|
|
9
|
+
assert format_filesize(1024 * 1024 * 1.5) == "1.5MB"
|
|
10
|
+
|
|
11
|
+
# Test with None
|
|
12
|
+
assert format_filesize(None) == "N/A"
|
|
@@ -17,7 +17,7 @@ def test_print_result():
|
|
|
17
17
|
sys.stdout = sys.__stdout__
|
|
18
18
|
|
|
19
19
|
# Check output
|
|
20
|
-
assert "Test
|
|
20
|
+
assert output.startswith("Test")
|
|
21
21
|
assert "Value" in output
|
|
22
22
|
|
|
23
23
|
# Test with status
|
|
@@ -26,7 +26,7 @@ def test_print_result():
|
|
|
26
26
|
print_result("Test", "Value", "good")
|
|
27
27
|
output = captured_output.getvalue()
|
|
28
28
|
sys.stdout = sys.__stdout__
|
|
29
|
-
assert "Test
|
|
29
|
+
assert output.startswith("Test")
|
|
30
30
|
assert "Value" in output
|
|
31
31
|
|
|
32
32
|
# Test with 'warning' status
|
|
@@ -35,7 +35,7 @@ def test_print_result():
|
|
|
35
35
|
print_result("Test", "Value", "warning")
|
|
36
36
|
output = captured_output.getvalue()
|
|
37
37
|
sys.stdout = sys.__stdout__
|
|
38
|
-
assert "Test
|
|
38
|
+
assert output.startswith("Test")
|
|
39
39
|
assert "Value" in output
|
|
40
40
|
|
|
41
41
|
# Test with 'bad' status
|
|
@@ -44,5 +44,5 @@ def test_print_result():
|
|
|
44
44
|
print_result("Test", "Value", "bad")
|
|
45
45
|
output = captured_output.getvalue()
|
|
46
46
|
sys.stdout = sys.__stdout__
|
|
47
|
-
assert "Test
|
|
47
|
+
assert output.startswith("Test")
|
|
48
48
|
assert "Value" in output
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Terminal formatting utilities for imgbytesizer.
|
|
3
|
-
"""
|
|
4
|
-
|
|
5
|
-
from typing import Optional
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
def format_filesize(size_bytes: Optional[int], precision: int = 2) -> str:
|
|
9
|
-
"""Format file size in a human-readable format."""
|
|
10
|
-
if size_bytes is None:
|
|
11
|
-
return "N/A"
|
|
12
|
-
|
|
13
|
-
if size_bytes < 1024:
|
|
14
|
-
return f"{size_bytes} B"
|
|
15
|
-
elif size_bytes < 1024 * 1024:
|
|
16
|
-
return f"{size_bytes / 1024:.{precision}f} KB"
|
|
17
|
-
else:
|
|
18
|
-
return f"{size_bytes / (1024 * 1024):.{precision}f} MB"
|
|
@@ -1,206 +0,0 @@
|
|
|
1
|
-
import logging
|
|
2
|
-
import sys
|
|
3
|
-
from typing import ClassVar, Dict, Optional, Tuple
|
|
4
|
-
|
|
5
|
-
from tabulate import tabulate
|
|
6
|
-
|
|
7
|
-
from .formatter import format_filesize
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
# ANSI Color Codes for beautiful terminal output
|
|
11
|
-
class Colors:
|
|
12
|
-
BLUE: ClassVar[str] = "\033[94m"
|
|
13
|
-
CYAN: ClassVar[str] = "\033[96m"
|
|
14
|
-
GREEN: ClassVar[str] = "\033[92m"
|
|
15
|
-
YELLOW: ClassVar[str] = "\033[93m"
|
|
16
|
-
RED: ClassVar[str] = "\033[91m"
|
|
17
|
-
ENDC: ClassVar[str] = "\033[0m"
|
|
18
|
-
BOLD: ClassVar[str] = "\033[1m"
|
|
19
|
-
UNDERLINE: ClassVar[str] = "\033[4m"
|
|
20
|
-
|
|
21
|
-
@staticmethod
|
|
22
|
-
def supports_color() -> bool:
|
|
23
|
-
"""Check if the terminal supports color output."""
|
|
24
|
-
# Add proper color support detection for different platforms
|
|
25
|
-
return sys.stdout.isatty()
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
class ColoredFormatter(logging.Formatter):
|
|
29
|
-
"""Custom formatter for colored console output."""
|
|
30
|
-
|
|
31
|
-
FORMATS: ClassVar[Dict[int, str]] = {
|
|
32
|
-
logging.DEBUG: Colors.BLUE + "%(message)s" + Colors.ENDC,
|
|
33
|
-
logging.INFO: "%(message)s",
|
|
34
|
-
logging.WARNING: Colors.YELLOW + "%(message)s" + Colors.ENDC,
|
|
35
|
-
logging.ERROR: Colors.RED + Colors.BOLD + "%(message)s" + Colors.ENDC,
|
|
36
|
-
logging.CRITICAL: Colors.RED + Colors.BOLD + "%(message)s" + Colors.ENDC,
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
def format(self, record: logging.LogRecord) -> str:
|
|
40
|
-
log_fmt = self.FORMATS.get(record.levelno)
|
|
41
|
-
formatter = logging.Formatter(log_fmt)
|
|
42
|
-
return formatter.format(record)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def setup_logger() -> logging.Logger:
|
|
46
|
-
"""Setup and return the application logger."""
|
|
47
|
-
logger = logging.getLogger("imgbytesizer")
|
|
48
|
-
|
|
49
|
-
if not logger.handlers:
|
|
50
|
-
handler = logging.StreamHandler(sys.stdout)
|
|
51
|
-
|
|
52
|
-
if Colors.supports_color():
|
|
53
|
-
handler.setFormatter(ColoredFormatter())
|
|
54
|
-
else:
|
|
55
|
-
handler.setFormatter(logging.Formatter("%(message)s"))
|
|
56
|
-
|
|
57
|
-
logger.addHandler(handler)
|
|
58
|
-
logger.setLevel(logging.INFO)
|
|
59
|
-
|
|
60
|
-
return logger
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
def print_progress_bar(
|
|
64
|
-
progress: int, total: int, prefix: str = "", suffix: str = "", length: int = 30
|
|
65
|
-
) -> None:
|
|
66
|
-
"""Print a progress bar with percentage."""
|
|
67
|
-
if not sys.stdout.isatty():
|
|
68
|
-
return # Don't print progress bars if not in a terminal
|
|
69
|
-
|
|
70
|
-
percent = min(100, int(100.0 * progress / total))
|
|
71
|
-
filled_length = int(length * progress // total)
|
|
72
|
-
bar = "█" * filled_length + "░" * (length - filled_length)
|
|
73
|
-
|
|
74
|
-
if Colors.supports_color():
|
|
75
|
-
print(
|
|
76
|
-
f"\r{prefix} |{Colors.GREEN}{bar}{Colors.ENDC}| {percent}% {suffix}",
|
|
77
|
-
end="\r",
|
|
78
|
-
)
|
|
79
|
-
else:
|
|
80
|
-
print(f"\r{prefix} |{bar}| {percent}% {suffix}", end="\r")
|
|
81
|
-
|
|
82
|
-
if progress == total:
|
|
83
|
-
print()
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
def print_result(name: str, value: str, status: Optional[str] = None) -> None:
|
|
87
|
-
"""Print a name-value pair with optional status color."""
|
|
88
|
-
value_color = Colors.ENDC
|
|
89
|
-
if status == "good":
|
|
90
|
-
value_color = Colors.GREEN
|
|
91
|
-
elif status == "warning":
|
|
92
|
-
value_color = Colors.YELLOW
|
|
93
|
-
elif status == "bad":
|
|
94
|
-
value_color = Colors.RED
|
|
95
|
-
|
|
96
|
-
if Colors.supports_color():
|
|
97
|
-
print(f" {Colors.BOLD}{name}:{Colors.ENDC} {value_color}{value}{Colors.ENDC}")
|
|
98
|
-
else:
|
|
99
|
-
print(f" {name}: {value}")
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def print_processing_step(step: int, description: str) -> None:
|
|
103
|
-
"""Print a processing step with a spinner."""
|
|
104
|
-
if not sys.stdout.isatty():
|
|
105
|
-
logger = logging.getLogger("imgbytesizer")
|
|
106
|
-
logger.info(description)
|
|
107
|
-
return
|
|
108
|
-
|
|
109
|
-
spinner = ["◐", "◓", "◑", "◒"]
|
|
110
|
-
|
|
111
|
-
if Colors.supports_color():
|
|
112
|
-
print(f"{Colors.BLUE}{spinner[step % len(spinner)]}{Colors.ENDC} {description}")
|
|
113
|
-
else:
|
|
114
|
-
print(f"* {description}")
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
def print_comparison_table(
|
|
118
|
-
original_size: int,
|
|
119
|
-
original_dimensions: Tuple[int, int],
|
|
120
|
-
final_size: int,
|
|
121
|
-
final_dimensions: Tuple[int, int],
|
|
122
|
-
target_size: int,
|
|
123
|
-
) -> None:
|
|
124
|
-
"""Print comparison table between original and processed image."""
|
|
125
|
-
if not sys.stdout.isatty():
|
|
126
|
-
# Use simpler output for non-terminal environments
|
|
127
|
-
logger = logging.getLogger("imgbytesizer")
|
|
128
|
-
logger.info(
|
|
129
|
-
f"Original: {original_dimensions[0]}×{original_dimensions[1]}, "
|
|
130
|
-
f"{format_filesize(original_size)}"
|
|
131
|
-
)
|
|
132
|
-
logger.info(
|
|
133
|
-
f"Processed: {final_dimensions[0]}×{final_dimensions[1]}, {format_filesize(final_size)}"
|
|
134
|
-
)
|
|
135
|
-
logger.info(f"Target: {format_filesize(target_size)}")
|
|
136
|
-
return
|
|
137
|
-
|
|
138
|
-
orig_dim = f"{original_dimensions[0]}×{original_dimensions[1]}"
|
|
139
|
-
new_dim = f"{final_dimensions[0]}×{final_dimensions[1]}"
|
|
140
|
-
orig_size = format_filesize(original_size)
|
|
141
|
-
new_size = format_filesize(final_size)
|
|
142
|
-
target = format_filesize(target_size)
|
|
143
|
-
diff = abs(final_size - target_size)
|
|
144
|
-
diff_pct = (diff / target_size) * 100
|
|
145
|
-
reduction = (
|
|
146
|
-
((original_size - final_size) / original_size) * 100 if original_size > final_size else 0
|
|
147
|
-
)
|
|
148
|
-
|
|
149
|
-
# Determine color based on how close to target
|
|
150
|
-
if diff_pct < 1:
|
|
151
|
-
diff_color = Colors.GREEN
|
|
152
|
-
elif diff_pct < 5:
|
|
153
|
-
diff_color = Colors.YELLOW
|
|
154
|
-
else:
|
|
155
|
-
diff_color = Colors.RED
|
|
156
|
-
|
|
157
|
-
if Colors.supports_color():
|
|
158
|
-
table = [
|
|
159
|
-
[
|
|
160
|
-
f"{Colors.BOLD}Dimensions{Colors.ENDC}",
|
|
161
|
-
f"{Colors.CYAN}{orig_dim}{Colors.ENDC}",
|
|
162
|
-
f"{Colors.GREEN}{new_dim}{Colors.ENDC}",
|
|
163
|
-
],
|
|
164
|
-
[
|
|
165
|
-
f"{Colors.BOLD}Size{Colors.ENDC}",
|
|
166
|
-
f"{Colors.CYAN}{orig_size}{Colors.ENDC}",
|
|
167
|
-
f"{Colors.GREEN}{new_size}{Colors.ENDC}",
|
|
168
|
-
],
|
|
169
|
-
[
|
|
170
|
-
f"{Colors.BOLD}Target Size{Colors.ENDC}",
|
|
171
|
-
"",
|
|
172
|
-
f"{Colors.BLUE}{target}{Colors.ENDC}",
|
|
173
|
-
],
|
|
174
|
-
[
|
|
175
|
-
f"{Colors.BOLD}Difference{Colors.ENDC}",
|
|
176
|
-
"",
|
|
177
|
-
f"{diff_color}{format_filesize(diff)} ({diff_pct:.1f}%){Colors.ENDC}",
|
|
178
|
-
],
|
|
179
|
-
[
|
|
180
|
-
f"{Colors.BOLD}Reduction{Colors.ENDC}",
|
|
181
|
-
"",
|
|
182
|
-
(
|
|
183
|
-
f"{Colors.CYAN}{reduction:.1f}% smaller{Colors.ENDC}"
|
|
184
|
-
if reduction else f"{Colors.YELLOW}N/A{Colors.ENDC}"
|
|
185
|
-
),
|
|
186
|
-
],
|
|
187
|
-
]
|
|
188
|
-
|
|
189
|
-
headers = [
|
|
190
|
-
f"{Colors.UNDERLINE}Metric{Colors.ENDC}",
|
|
191
|
-
f"{Colors.UNDERLINE}Original{Colors.ENDC}",
|
|
192
|
-
f"{Colors.UNDERLINE}Processed{Colors.ENDC}",
|
|
193
|
-
]
|
|
194
|
-
else:
|
|
195
|
-
table = [
|
|
196
|
-
["Dimensions", orig_dim, new_dim],
|
|
197
|
-
["Size", orig_size, new_size],
|
|
198
|
-
["Target Size", "", target],
|
|
199
|
-
["Difference", "", f"{format_filesize(diff)} ({diff_pct:.1f}%)"],
|
|
200
|
-
["Reduction", "", f"{reduction:.1f}% smaller" if reduction else "N/A"],
|
|
201
|
-
]
|
|
202
|
-
|
|
203
|
-
headers = ["Metric", "Original", "Processed"]
|
|
204
|
-
|
|
205
|
-
print()
|
|
206
|
-
print(tabulate(table, headers=headers, tablefmt="rounded_grid"))
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
from imgbytesizer.formatter import format_filesize
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
def test_format_filesize():
|
|
5
|
-
# Test various file sizes
|
|
6
|
-
assert format_filesize(500) == "500 B"
|
|
7
|
-
assert format_filesize(1024) == "1.00 KB"
|
|
8
|
-
assert format_filesize(1024 * 1024) == "1.00 MB"
|
|
9
|
-
assert format_filesize(1024 * 1024 * 1.5) == "1.50 MB"
|
|
10
|
-
|
|
11
|
-
# Test with different precision
|
|
12
|
-
assert format_filesize(1024, precision=0) == "1 KB"
|
|
13
|
-
assert format_filesize(1024 * 1024 * 1.234, precision=3) == "1.234 MB"
|
|
14
|
-
|
|
15
|
-
# Test with None
|
|
16
|
-
assert format_filesize(None) == "N/A"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|