imgbytesizer 0.2.1__tar.gz → 0.2.2__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.1 → imgbytesizer-0.2.2}/PKG-INFO +2 -1
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/README.md +1 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/imgbytesizer/__init__.py +1 -1
- imgbytesizer-0.2.2/imgbytesizer/formatter.py +18 -0
- imgbytesizer-0.2.2/imgbytesizer/logger.py +206 -0
- imgbytesizer-0.2.2/imgbytesizer/main.py +104 -0
- imgbytesizer-0.2.2/imgbytesizer/resizer.py +547 -0
- imgbytesizer-0.2.2/imgbytesizer/utils.py +106 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/PKG-INFO +2 -1
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/SOURCES.txt +2 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/pyproject.toml +1 -1
- imgbytesizer-0.2.2/tests/test_formatter.py +16 -0
- imgbytesizer-0.2.2/tests/test_logger.py +48 -0
- imgbytesizer-0.2.2/tests/test_main.py +128 -0
- imgbytesizer-0.2.2/tests/test_resizer.py +291 -0
- imgbytesizer-0.2.2/tests/test_utils.py +99 -0
- imgbytesizer-0.2.1/imgbytesizer/formatter.py +0 -172
- imgbytesizer-0.2.1/imgbytesizer/logger.py +0 -56
- imgbytesizer-0.2.1/imgbytesizer/main.py +0 -112
- imgbytesizer-0.2.1/imgbytesizer/resizer.py +0 -568
- imgbytesizer-0.2.1/imgbytesizer/utils.py +0 -108
- imgbytesizer-0.2.1/tests/test_formatter.py +0 -48
- imgbytesizer-0.2.1/tests/test_resizer.py +0 -217
- imgbytesizer-0.2.1/tests/test_utils.py +0 -94
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/LICENSE +0 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/dependency_links.txt +0 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/entry_points.txt +0 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/requires.txt +0 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/top_level.txt +0 -0
- {imgbytesizer-0.2.1 → imgbytesizer-0.2.2}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: imgbytesizer
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
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
|
|
@@ -16,6 +16,7 @@ Dynamic: license-file
|
|
|
16
16
|
|
|
17
17
|
[](https://pypi.org/project/imgbytesizer/)
|
|
18
18
|
[](https://pepy.tech/projects/imgbytesizer)
|
|
19
|
+
[](https://codecov.io/gh/pyyupsk/imgbytesizer)
|
|
19
20
|
|
|
20
21
|
ImgByteSizer is a command-line tool that precisely resizes and optimizes images to match a specific file size while maintaining the best possible quality.
|
|
21
22
|
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://pypi.org/project/imgbytesizer/)
|
|
4
4
|
[](https://pepy.tech/projects/imgbytesizer)
|
|
5
|
+
[](https://codecov.io/gh/pyyupsk/imgbytesizer)
|
|
5
6
|
|
|
6
7
|
ImgByteSizer is a command-line tool that precisely resizes and optimizes images to match a specific file size while maintaining the best possible quality.
|
|
7
8
|
|
|
@@ -0,0 +1,18 @@
|
|
|
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"
|
|
@@ -0,0 +1,206 @@
|
|
|
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"))
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command-line interface for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import logging
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .logger import setup_logger
|
|
11
|
+
from .resizer import resize_to_target_filesize
|
|
12
|
+
from .utils import IMG_FORMATS, parse_filesize
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> int:
|
|
16
|
+
"""Main entry point for the CLI."""
|
|
17
|
+
# Setup logger
|
|
18
|
+
logger = setup_logger()
|
|
19
|
+
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
description="Resize an image to match a target file size",
|
|
22
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
23
|
+
epilog="""
|
|
24
|
+
Examples:
|
|
25
|
+
%(prog)s image.jpg 500KB # Resize to 500 KB
|
|
26
|
+
%(prog)s photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
|
|
27
|
+
%(prog)s image.jpg 100KB -f webp # Resize and convert to WebP
|
|
28
|
+
%(prog)s large.jpg 50KB --min-dimension 200 # Ensure min dimension is 200px
|
|
29
|
+
%(prog)s -v # Show version information
|
|
30
|
+
""",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
parser.add_argument("image_path", nargs="?", help="Path to the input image")
|
|
34
|
+
parser.add_argument("target_size", nargs="?", help='Target file size (e.g., "1MB", "500KB")')
|
|
35
|
+
parser.add_argument("-o", "--output", help="Output path (default: input_resized.ext)")
|
|
36
|
+
parser.add_argument("-f", "--format", choices=IMG_FORMATS, help="Output format")
|
|
37
|
+
parser.add_argument("--min-dimension", type=int, help="Minimum width/height in pixels")
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--no-exact",
|
|
40
|
+
action="store_true",
|
|
41
|
+
help="Do not pad file to get exact target size",
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument("-v", "--version", action="store_true", help="Show version information")
|
|
44
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
45
|
+
parser.add_argument("-q", "--quiet", action="store_true", help="Minimal output")
|
|
46
|
+
|
|
47
|
+
# Handle version flag before checking required arguments
|
|
48
|
+
args = parser.parse_args()
|
|
49
|
+
|
|
50
|
+
# Handle version request
|
|
51
|
+
if args.version:
|
|
52
|
+
from . import __version__
|
|
53
|
+
|
|
54
|
+
print(f"imgbytesizer v{__version__}")
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
# Set logging level
|
|
58
|
+
if args.debug:
|
|
59
|
+
logger.setLevel(logging.DEBUG)
|
|
60
|
+
elif args.quiet:
|
|
61
|
+
logger.setLevel(logging.WARNING)
|
|
62
|
+
|
|
63
|
+
# Handle no arguments case with nice help
|
|
64
|
+
if args.image_path is None or args.target_size is None:
|
|
65
|
+
parser.print_help()
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
# Validate input file exists
|
|
69
|
+
image_path = Path(args.image_path)
|
|
70
|
+
if not image_path.exists():
|
|
71
|
+
logger.error(f"Input file not found: {args.image_path}")
|
|
72
|
+
return 1
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
target_bytes = parse_filesize(args.target_size)
|
|
76
|
+
except ValueError as e:
|
|
77
|
+
logger.error(f"Error: {e}")
|
|
78
|
+
return 1
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
output_path = resize_to_target_filesize(
|
|
82
|
+
args.image_path,
|
|
83
|
+
target_bytes,
|
|
84
|
+
args.output,
|
|
85
|
+
args.format,
|
|
86
|
+
args.min_dimension,
|
|
87
|
+
exact_size=not args.no_exact,
|
|
88
|
+
quiet=args.quiet,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
logger.debug(f"Successfully processed image: {output_path}")
|
|
92
|
+
return 0
|
|
93
|
+
except KeyboardInterrupt:
|
|
94
|
+
logger.warning("Process interrupted by user.")
|
|
95
|
+
return 130
|
|
96
|
+
except Exception as e:
|
|
97
|
+
logger.error(f"Error: {str(e)}")
|
|
98
|
+
if args.debug:
|
|
99
|
+
logger.exception("Detailed error information:")
|
|
100
|
+
return 1
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
sys.exit(main())
|