imgbytesizer 0.1.0__tar.gz → 0.2.0__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.4
2
2
  Name: imgbytesizer
3
- Version: 0.1.0
3
+ Version: 0.2.0
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
@@ -60,7 +60,7 @@ imgbytesizer large_image.jpg 300KB --min-dimension 400
60
60
  ### Command-Line Options
61
61
 
62
62
  ```bash
63
- usage: imgbytesizer [-h] [-o OUTPUT] [-f FORMAT] [--min-dimension MIN_DIMENSION] [--no-exact] image_path target_size
63
+ usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [-v] [--debug] [-q] [image_path] [target_size]
64
64
 
65
65
  Resize an image to match a target file size
66
66
 
@@ -71,10 +71,14 @@ positional arguments:
71
71
  options:
72
72
  -h, --help show this help message and exit
73
73
  -o, --output OUTPUT Output path (default: input_resized.ext)
74
- -f, --format FORMAT Output format (jpg, png, webp)
74
+ -f, --format {jpg,jpeg,png,webp}
75
+ Output format
75
76
  --min-dimension MIN_DIMENSION
76
77
  Minimum width/height in pixels
77
78
  --no-exact Do not pad file to get exact target size
79
+ -v, --version Show version information
80
+ --debug Enable debug logging
81
+ -q, --quiet Minimal output
78
82
  ```
79
83
 
80
84
  ## How It Works
@@ -91,29 +95,38 @@ The tool prioritizes maintaining the highest possible quality while meeting the
91
95
  ## Example Output
92
96
 
93
97
  ```
94
- ◐ Opening photo.jpg
95
- File: photo.jpg
96
- Format: JPEG
97
- Dimensions: 4032 × 3024 pixels
98
- Size: 2.5 MB
99
- Target size: 500 KB
100
-
98
+ ◐ Opening image.png
99
+ File: image.png
100
+ Format: WEBP
101
+ Dimensions: 1920 × 1080 pixels
102
+ Size: 1.09 MB
103
+ Target size: 250.00 KB
101
104
  Trying quality adjustment without resizing...
102
- Testing quality 48 |██████████████████████████████| 100% Size: 497.3 KB
103
-
104
- ✓ Found optimal quality: 48 (size: 497.3 KB)
105
-
106
- ┌────────────┬──────────────┬───────────────┐
107
- │ Metric │ Original │ Processed │
108
- ├────────────┼──────────────┼───────────────┤
109
- │ Dimensions │ 4032×3024 │ 4032×3024 │
110
- │ Size │ 2.5 MB │ 497.3 KB │
111
- │ Target Size│ │ 500 KB │
112
- │ Difference │ │ 2.7 KB (0.5%) │
113
- │ Reduction │ │ 80.1% smaller │
114
- └────────────┴──────────────┴───────────────┘
115
- Time taken: 0.87 seconds
116
- Output file: photo_resized.jpg
105
+ Testing quality 95 |█████████████████████░░░░░░░░░| 70% Size: 145.37 KB
106
+ ✓ Found optimal quality: 95 (size: 145.37 KB)
107
+ Adjusting to exact target size...
108
+ Optimizing quality for exact size match...
109
+ Testing quality 96 |██████████████████████████████| 100%
110
+
111
+ ✓ Quality adjusted to 96: 146.07 KB
112
+ Adding 103.93 KB padding...
113
+ ✓ File padded to exact size
114
+
115
+ ╭─────────────┬────────────┬───────────────╮
116
+ │ Metric │ Original │ Processed │
117
+ ├─────────────┼────────────┼───────────────┤
118
+ │ Dimensions │ 1920×1080 │ 1920×1080 │
119
+ ├─────────────┼────────────┼───────────────┤
120
+ │ Size │ 1.09 MB │ 250.00 KB │
121
+ ├─────────────┼────────────┼───────────────┤
122
+ │ Target Size │ │ 250.00 KB │
123
+ ├─────────────┼────────────┼───────────────┤
124
+ │ Difference │ │ 0 B (0.0%) │
125
+ ├─────────────┼────────────┼───────────────┤
126
+ │ Reduction │ │ 77.6% smaller │
127
+ ╰─────────────┴────────────┴───────────────╯
128
+ Time taken: 3.77 seconds
129
+ Output file: image_resized.webp
117
130
  ```
118
131
 
119
132
  ## Real Use Cases
@@ -46,7 +46,7 @@ imgbytesizer large_image.jpg 300KB --min-dimension 400
46
46
  ### Command-Line Options
47
47
 
48
48
  ```bash
49
- usage: imgbytesizer [-h] [-o OUTPUT] [-f FORMAT] [--min-dimension MIN_DIMENSION] [--no-exact] image_path target_size
49
+ usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [-v] [--debug] [-q] [image_path] [target_size]
50
50
 
51
51
  Resize an image to match a target file size
52
52
 
@@ -57,10 +57,14 @@ positional arguments:
57
57
  options:
58
58
  -h, --help show this help message and exit
59
59
  -o, --output OUTPUT Output path (default: input_resized.ext)
60
- -f, --format FORMAT Output format (jpg, png, webp)
60
+ -f, --format {jpg,jpeg,png,webp}
61
+ Output format
61
62
  --min-dimension MIN_DIMENSION
62
63
  Minimum width/height in pixels
63
64
  --no-exact Do not pad file to get exact target size
65
+ -v, --version Show version information
66
+ --debug Enable debug logging
67
+ -q, --quiet Minimal output
64
68
  ```
65
69
 
66
70
  ## How It Works
@@ -77,29 +81,38 @@ The tool prioritizes maintaining the highest possible quality while meeting the
77
81
  ## Example Output
78
82
 
79
83
  ```
80
- ◐ Opening photo.jpg
81
- File: photo.jpg
82
- Format: JPEG
83
- Dimensions: 4032 × 3024 pixels
84
- Size: 2.5 MB
85
- Target size: 500 KB
86
-
84
+ ◐ Opening image.png
85
+ File: image.png
86
+ Format: WEBP
87
+ Dimensions: 1920 × 1080 pixels
88
+ Size: 1.09 MB
89
+ Target size: 250.00 KB
87
90
  Trying quality adjustment without resizing...
88
- Testing quality 48 |██████████████████████████████| 100% Size: 497.3 KB
89
-
90
- ✓ Found optimal quality: 48 (size: 497.3 KB)
91
-
92
- ┌────────────┬──────────────┬───────────────┐
93
- │ Metric │ Original │ Processed │
94
- ├────────────┼──────────────┼───────────────┤
95
- │ Dimensions │ 4032×3024 │ 4032×3024 │
96
- │ Size │ 2.5 MB │ 497.3 KB │
97
- │ Target Size│ │ 500 KB │
98
- │ Difference │ │ 2.7 KB (0.5%) │
99
- │ Reduction │ │ 80.1% smaller │
100
- └────────────┴──────────────┴───────────────┘
101
- Time taken: 0.87 seconds
102
- Output file: photo_resized.jpg
91
+ Testing quality 95 |█████████████████████░░░░░░░░░| 70% Size: 145.37 KB
92
+ ✓ Found optimal quality: 95 (size: 145.37 KB)
93
+ Adjusting to exact target size...
94
+ Optimizing quality for exact size match...
95
+ Testing quality 96 |██████████████████████████████| 100%
96
+
97
+ ✓ Quality adjusted to 96: 146.07 KB
98
+ Adding 103.93 KB padding...
99
+ ✓ File padded to exact size
100
+
101
+ ╭─────────────┬────────────┬───────────────╮
102
+ │ Metric │ Original │ Processed │
103
+ ├─────────────┼────────────┼───────────────┤
104
+ │ Dimensions │ 1920×1080 │ 1920×1080 │
105
+ ├─────────────┼────────────┼───────────────┤
106
+ │ Size │ 1.09 MB │ 250.00 KB │
107
+ ├─────────────┼────────────┼───────────────┤
108
+ │ Target Size │ │ 250.00 KB │
109
+ ├─────────────┼────────────┼───────────────┤
110
+ │ Difference │ │ 0 B (0.0%) │
111
+ ├─────────────┼────────────┼───────────────┤
112
+ │ Reduction │ │ 77.6% smaller │
113
+ ╰─────────────┴────────────┴───────────────╯
114
+ Time taken: 3.77 seconds
115
+ Output file: image_resized.webp
103
116
  ```
104
117
 
105
118
  ## Real Use Cases
@@ -0,0 +1,7 @@
1
+ """
2
+ imgbytesizer: A CLI tool to resize images to a target file size.
3
+ """
4
+
5
+ __version__ = "0.2.0"
6
+ __author__ = "pyyupsk"
7
+ __description__ = "Resize images to match a target file size"
@@ -0,0 +1,162 @@
1
+ """
2
+ Terminal formatting utilities for imgbytesizer.
3
+ """
4
+
5
+ import sys
6
+ import logging
7
+ from tabulate import tabulate
8
+
9
+ from .logger import Colors
10
+
11
+
12
+ def format_filesize(size_bytes, precision=2):
13
+ """Format file size in a human-readable format."""
14
+ if size_bytes < 1024:
15
+ return f"{size_bytes} B"
16
+ elif size_bytes < 1024 * 1024:
17
+ return f"{size_bytes/1024:.{precision}f} KB"
18
+ else:
19
+ return f"{size_bytes/(1024*1024):.{precision}f} MB"
20
+
21
+
22
+ def print_progress_bar(progress, total, prefix="", suffix="", length=30):
23
+ """Print a progress bar with percentage."""
24
+ if not sys.stdout.isatty():
25
+ return # Don't print progress bars if not in a terminal
26
+
27
+ percent = min(100, int(100.0 * progress / total))
28
+ filled_length = int(length * progress // total)
29
+ bar = "█" * filled_length + "░" * (length - filled_length)
30
+
31
+ if Colors.supports_color():
32
+ print(
33
+ f"\r{prefix} |{Colors.GREEN}{bar}{Colors.ENDC}| {percent}% {suffix}",
34
+ end="\r",
35
+ )
36
+ else:
37
+ print(f"\r{prefix} |{bar}| {percent}% {suffix}", end="\r")
38
+
39
+ if progress == total:
40
+ print()
41
+
42
+
43
+ def print_result(name, value, status=None):
44
+ """Print a name-value pair with optional status color."""
45
+ value_color = Colors.ENDC
46
+ if status == "good":
47
+ value_color = Colors.GREEN
48
+ elif status == "warning":
49
+ value_color = Colors.YELLOW
50
+ elif status == "bad":
51
+ value_color = Colors.RED
52
+
53
+ if Colors.supports_color():
54
+ print(f" {Colors.BOLD}{name}:{Colors.ENDC} {value_color}{value}{Colors.ENDC}")
55
+ else:
56
+ print(f" {name}: {value}")
57
+
58
+
59
+ def print_processing_step(step, description):
60
+ """Print a processing step with a spinner."""
61
+ if not sys.stdout.isatty():
62
+ logger = logging.getLogger("imgbytesizer")
63
+ logger.info(description)
64
+ return
65
+
66
+ spinner = ["◐", "◓", "◑", "◒"]
67
+
68
+ if Colors.supports_color():
69
+ print(f"{Colors.BLUE}{spinner[step % len(spinner)]}{Colors.ENDC} {description}")
70
+ else:
71
+ print(f"* {description}")
72
+
73
+
74
+ def print_comparison_table(
75
+ original_size, original_dimensions, final_size, final_dimensions, target_size
76
+ ):
77
+ """Print comparison table between original and processed image."""
78
+ if not sys.stdout.isatty():
79
+ # Use simpler output for non-terminal environments
80
+ logger = logging.getLogger("imgbytesizer")
81
+ logger.info(
82
+ f"Original: {original_dimensions[0]}×{original_dimensions[1]}, "
83
+ f"{format_filesize(original_size)}"
84
+ )
85
+ logger.info(
86
+ f"Processed: {final_dimensions[0]}×{final_dimensions[1]}, {format_filesize(final_size)}"
87
+ )
88
+ logger.info(f"Target: {format_filesize(target_size)}")
89
+ return
90
+
91
+ orig_dim = f"{original_dimensions[0]}×{original_dimensions[1]}"
92
+ new_dim = f"{final_dimensions[0]}×{final_dimensions[1]}"
93
+ orig_size = format_filesize(original_size)
94
+ new_size = format_filesize(final_size)
95
+ target = format_filesize(target_size)
96
+ diff = abs(final_size - target_size)
97
+ diff_pct = (diff / target_size) * 100
98
+ reduction = (
99
+ ((original_size - final_size) / original_size) * 100
100
+ if original_size > final_size
101
+ else 0
102
+ )
103
+
104
+ # Determine color based on how close to target
105
+ if diff_pct < 1:
106
+ diff_color = Colors.GREEN
107
+ elif diff_pct < 5:
108
+ diff_color = Colors.YELLOW
109
+ else:
110
+ diff_color = Colors.RED
111
+
112
+ if Colors.supports_color():
113
+ table = [
114
+ [
115
+ f"{Colors.BOLD}Dimensions{Colors.ENDC}",
116
+ f"{Colors.CYAN}{orig_dim}{Colors.ENDC}",
117
+ f"{Colors.GREEN}{new_dim}{Colors.ENDC}",
118
+ ],
119
+ [
120
+ f"{Colors.BOLD}Size{Colors.ENDC}",
121
+ f"{Colors.CYAN}{orig_size}{Colors.ENDC}",
122
+ f"{Colors.GREEN}{new_size}{Colors.ENDC}",
123
+ ],
124
+ [
125
+ f"{Colors.BOLD}Target Size{Colors.ENDC}",
126
+ "",
127
+ f"{Colors.BLUE}{target}{Colors.ENDC}",
128
+ ],
129
+ [
130
+ f"{Colors.BOLD}Difference{Colors.ENDC}",
131
+ "",
132
+ f"{diff_color}{format_filesize(diff)} ({diff_pct:.1f}%){Colors.ENDC}",
133
+ ],
134
+ [
135
+ f"{Colors.BOLD}Reduction{Colors.ENDC}",
136
+ "",
137
+ (
138
+ f"{Colors.CYAN}{reduction:.1f}% smaller{Colors.ENDC}"
139
+ if reduction
140
+ else f"{Colors.YELLOW}N/A{Colors.ENDC}"
141
+ ),
142
+ ],
143
+ ]
144
+
145
+ headers = [
146
+ f"{Colors.UNDERLINE}Metric{Colors.ENDC}",
147
+ f"{Colors.UNDERLINE}Original{Colors.ENDC}",
148
+ f"{Colors.UNDERLINE}Processed{Colors.ENDC}",
149
+ ]
150
+ else:
151
+ table = [
152
+ ["Dimensions", orig_dim, new_dim],
153
+ ["Size", orig_size, new_size],
154
+ ["Target Size", "", target],
155
+ ["Difference", "", f"{format_filesize(diff)} ({diff_pct:.1f}%)"],
156
+ ["Reduction", "", f"{reduction:.1f}% smaller" if reduction else "N/A"],
157
+ ]
158
+
159
+ headers = ["Metric", "Original", "Processed"]
160
+
161
+ print()
162
+ print(tabulate(table, headers=headers, tablefmt="rounded_grid"))
@@ -0,0 +1,55 @@
1
+ import sys
2
+ import logging
3
+
4
+
5
+ # ANSI Color Codes for beautiful terminal output
6
+ class Colors:
7
+ BLUE = "\033[94m"
8
+ CYAN = "\033[96m"
9
+ GREEN = "\033[92m"
10
+ YELLOW = "\033[93m"
11
+ RED = "\033[91m"
12
+ ENDC = "\033[0m"
13
+ BOLD = "\033[1m"
14
+ UNDERLINE = "\033[4m"
15
+
16
+ @staticmethod
17
+ def supports_color():
18
+ """Check if the terminal supports color output."""
19
+ # Add proper color support detection for different platforms
20
+ return sys.stdout.isatty()
21
+
22
+
23
+ class ColoredFormatter(logging.Formatter):
24
+ """Custom formatter for colored console output."""
25
+
26
+ FORMATS = {
27
+ logging.DEBUG: Colors.BLUE + "%(message)s" + Colors.ENDC,
28
+ logging.INFO: "%(message)s",
29
+ logging.WARNING: Colors.YELLOW + "%(message)s" + Colors.ENDC,
30
+ logging.ERROR: Colors.RED + Colors.BOLD + "%(message)s" + Colors.ENDC,
31
+ logging.CRITICAL: Colors.RED + Colors.BOLD + "%(message)s" + Colors.ENDC,
32
+ }
33
+
34
+ def format(self, record):
35
+ log_fmt = self.FORMATS.get(record.levelno)
36
+ formatter = logging.Formatter(log_fmt)
37
+ return formatter.format(record)
38
+
39
+
40
+ def setup_logger():
41
+ """Setup and return the application logger."""
42
+ logger = logging.getLogger("imgbytesizer")
43
+
44
+ if not logger.handlers:
45
+ handler = logging.StreamHandler(sys.stdout)
46
+
47
+ if Colors.supports_color():
48
+ handler.setFormatter(ColoredFormatter())
49
+ else:
50
+ handler.setFormatter(logging.Formatter("%(message)s"))
51
+
52
+ logger.addHandler(handler)
53
+ logger.setLevel(logging.INFO)
54
+
55
+ return logger
@@ -0,0 +1,112 @@
1
+ """
2
+ Command-line interface for imgbytesizer.
3
+ """
4
+
5
+ import sys
6
+ import argparse
7
+ import logging
8
+ from pathlib import Path
9
+
10
+ from .logger import setup_logger
11
+ from .resizer import resize_to_target_filesize
12
+ from .utils import parse_filesize, IMG_FORMATS
13
+
14
+
15
+ def main():
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(
35
+ "target_size", nargs="?", help='Target file size (e.g., "1MB", "500KB")'
36
+ )
37
+ parser.add_argument(
38
+ "-o", "--output", help="Output path (default: input_resized.ext)"
39
+ )
40
+ parser.add_argument("-f", "--format", choices=IMG_FORMATS, help="Output format")
41
+ parser.add_argument(
42
+ "--min-dimension", type=int, help="Minimum width/height in pixels"
43
+ )
44
+ parser.add_argument(
45
+ "--no-exact",
46
+ action="store_true",
47
+ help="Do not pad file to get exact target size",
48
+ )
49
+ parser.add_argument(
50
+ "-v", "--version", action="store_true", help="Show version information"
51
+ )
52
+ parser.add_argument("--debug", action="store_true", help="Enable debug logging")
53
+ parser.add_argument("-q", "--quiet", action="store_true", help="Minimal output")
54
+
55
+ # Handle version flag before checking required arguments
56
+ args = parser.parse_args()
57
+
58
+ # Handle version request
59
+ if args.version:
60
+ from . import __version__
61
+
62
+ print(f"imgbytesizer v{__version__}")
63
+ return 0
64
+
65
+ # Set logging level
66
+ if args.debug:
67
+ logger.setLevel(logging.DEBUG)
68
+ elif args.quiet:
69
+ logger.setLevel(logging.WARNING)
70
+
71
+ # Handle no arguments case with nice help
72
+ if args.image_path is None or args.target_size is None:
73
+ parser.print_help()
74
+ return 0
75
+
76
+ # Validate input file exists
77
+ image_path = Path(args.image_path)
78
+ if not image_path.exists():
79
+ logger.error(f"Input file not found: {args.image_path}")
80
+ return 1
81
+
82
+ try:
83
+ target_bytes = parse_filesize(args.target_size)
84
+ except ValueError as e:
85
+ logger.error(f"Error: {e}")
86
+ return 1
87
+
88
+ try:
89
+ output_path = resize_to_target_filesize(
90
+ args.image_path,
91
+ target_bytes,
92
+ args.output,
93
+ args.format,
94
+ args.min_dimension,
95
+ exact_size=not args.no_exact,
96
+ quiet=args.quiet,
97
+ )
98
+
99
+ logger.debug(f"Successfully processed image: {output_path}")
100
+ return 0
101
+ except KeyboardInterrupt:
102
+ logger.warning("Process interrupted by user.")
103
+ return 130
104
+ except Exception as e:
105
+ logger.error(f"Error: {str(e)}")
106
+ if args.debug:
107
+ logger.exception("Detailed error information:")
108
+ return 1
109
+
110
+
111
+ if __name__ == "__main__":
112
+ sys.exit(main())