imgbytesizer 0.2.1__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.
Files changed (30) hide show
  1. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/PKG-INFO +17 -3
  2. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/README.md +16 -2
  3. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/imgbytesizer/__init__.py +1 -1
  4. imgbytesizer-0.2.3/imgbytesizer/formatter.py +17 -0
  5. imgbytesizer-0.2.3/imgbytesizer/logger.py +128 -0
  6. imgbytesizer-0.2.3/imgbytesizer/main.py +121 -0
  7. imgbytesizer-0.2.3/imgbytesizer/resizer.py +571 -0
  8. imgbytesizer-0.2.3/imgbytesizer/utils.py +104 -0
  9. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/PKG-INFO +17 -3
  10. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/SOURCES.txt +2 -0
  11. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/pyproject.toml +1 -1
  12. imgbytesizer-0.2.3/tests/test_formatter.py +12 -0
  13. imgbytesizer-0.2.3/tests/test_logger.py +48 -0
  14. imgbytesizer-0.2.3/tests/test_main.py +128 -0
  15. imgbytesizer-0.2.3/tests/test_resizer.py +291 -0
  16. imgbytesizer-0.2.3/tests/test_utils.py +99 -0
  17. imgbytesizer-0.2.1/imgbytesizer/formatter.py +0 -172
  18. imgbytesizer-0.2.1/imgbytesizer/logger.py +0 -56
  19. imgbytesizer-0.2.1/imgbytesizer/main.py +0 -112
  20. imgbytesizer-0.2.1/imgbytesizer/resizer.py +0 -568
  21. imgbytesizer-0.2.1/imgbytesizer/utils.py +0 -108
  22. imgbytesizer-0.2.1/tests/test_formatter.py +0 -48
  23. imgbytesizer-0.2.1/tests/test_resizer.py +0 -217
  24. imgbytesizer-0.2.1/tests/test_utils.py +0 -94
  25. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/LICENSE +0 -0
  26. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/dependency_links.txt +0 -0
  27. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/entry_points.txt +0 -0
  28. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/requires.txt +0 -0
  29. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/imgbytesizer.egg-info/top_level.txt +0 -0
  30. {imgbytesizer-0.2.1 → imgbytesizer-0.2.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: imgbytesizer
3
- Version: 0.2.1
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
@@ -16,6 +16,7 @@ Dynamic: license-file
16
16
 
17
17
  [![PyPI version](https://img.shields.io/pypi/v/imgbytesizer.svg)](https://pypi.org/project/imgbytesizer/)
18
18
  [![PyPI Downloads](https://static.pepy.tech/badge/imgbytesizer)](https://pepy.tech/projects/imgbytesizer)
19
+ [![codecov](https://codecov.io/gh/pyyupsk/imgbytesizer/graph/badge.svg?token=GJH6N3ZAJS)](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
 
@@ -60,7 +61,7 @@ imgbytesizer large_image.jpg 300KB --min-dimension 400
60
61
  ### Command-Line Options
61
62
 
62
63
  ```bash
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
+ usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [--debug] [-q] [-v] [image_path] [target_size]
64
65
 
65
66
  Resize an image to match a target file size
66
67
 
@@ -70,15 +71,28 @@ positional arguments:
70
71
 
71
72
  options:
72
73
  -h, --help show this help message and exit
74
+ -v, --version Show version information
75
+
76
+ primary options:
73
77
  -o, --output OUTPUT Output path (default: input_resized.ext)
74
78
  -f, --format {jpg,jpeg,png,webp}
75
79
  Output format
80
+
81
+ advanced options:
76
82
  --min-dimension MIN_DIMENSION
77
83
  Minimum width/height in pixels
78
84
  --no-exact Do not pad file to get exact target size
79
- -v, --version Show version information
85
+
86
+ utility:
80
87
  --debug Enable debug logging
81
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
82
96
  ```
83
97
 
84
98
  ## How It Works
@@ -2,6 +2,7 @@
2
2
 
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
+ [![codecov](https://codecov.io/gh/pyyupsk/imgbytesizer/graph/badge.svg?token=GJH6N3ZAJS)](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
 
@@ -46,7 +47,7 @@ imgbytesizer large_image.jpg 300KB --min-dimension 400
46
47
  ### Command-Line Options
47
48
 
48
49
  ```bash
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
+ usage: imgbytesizer [-h] [-o OUTPUT] [-f {jpg,jpeg,png,webp}] [--min-dimension MIN_DIMENSION] [--no-exact] [--debug] [-q] [-v] [image_path] [target_size]
50
51
 
51
52
  Resize an image to match a target file size
52
53
 
@@ -56,15 +57,28 @@ positional arguments:
56
57
 
57
58
  options:
58
59
  -h, --help show this help message and exit
60
+ -v, --version Show version information
61
+
62
+ primary options:
59
63
  -o, --output OUTPUT Output path (default: input_resized.ext)
60
64
  -f, --format {jpg,jpeg,png,webp}
61
65
  Output format
66
+
67
+ advanced options:
62
68
  --min-dimension MIN_DIMENSION
63
69
  Minimum width/height in pixels
64
70
  --no-exact Do not pad file to get exact target size
65
- -v, --version Show version information
71
+
72
+ utility:
66
73
  --debug Enable debug logging
67
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
68
82
  ```
69
83
 
70
84
  ## How It Works
@@ -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.1"
5
+ __version__: str = "0.2.3"
6
6
  __author__: str = "pyyupsk"
7
7
  __description__: str = "Resize images to match a target file size"
@@ -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()
@@ -0,0 +1,121 @@
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 pyfiglet import Figlet
11
+
12
+ from .logger import setup_logger
13
+ from .resizer import resize_to_target_filesize
14
+ from .utils import IMG_FORMATS, parse_filesize
15
+
16
+ f: Figlet = Figlet(font='slant')
17
+
18
+
19
+ def main() -> int:
20
+ """Main entry point for the CLI."""
21
+ # Setup logger
22
+ logger: logging.Logger = setup_logger()
23
+
24
+ print(f.renderText('ImgByteSizer'))
25
+
26
+ parser: argparse.ArgumentParser = argparse.ArgumentParser(
27
+ description="Resize an image to match a target file size",
28
+ formatter_class=argparse.RawDescriptionHelpFormatter,
29
+ epilog="""
30
+ examples:
31
+ %(prog)s image.jpg 500KB # Resize to 500 KB
32
+ %(prog)s photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
33
+ %(prog)s image.jpg 100KB -f webp # Resize and convert to WebP
34
+ %(prog)s large.jpg 50KB --min-dimension 200 # Ensure min dimension is 200px
35
+ %(prog)s -v # Show version information
36
+ """,
37
+ )
38
+
39
+ # Version
40
+ parser.add_argument("-v", "--version", action="store_true", help="Show version information")
41
+
42
+ parser.add_argument("image_path", nargs="?", help="Path to the input image")
43
+ parser.add_argument("target_size", nargs="?", help='Target file size (e.g., "1MB", "500KB")')
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(
54
+ "--no-exact",
55
+ action="store_true",
56
+ help="Do not pad file to get exact target size",
57
+ )
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")
63
+
64
+ # Handle version flag before checking required arguments
65
+ args: argparse.Namespace = parser.parse_args()
66
+
67
+ # Handle version request
68
+ if args.version:
69
+ from . import __version__
70
+
71
+ print(f"imgbytesizer v{__version__}")
72
+ return 0
73
+
74
+ # Set logging level
75
+ if args.debug:
76
+ logger.setLevel(logging.DEBUG)
77
+ elif args.quiet:
78
+ logger.setLevel(logging.WARNING)
79
+
80
+ # Handle no arguments case with nice help
81
+ if args.image_path is None or args.target_size is None:
82
+ parser.print_help()
83
+ return 0
84
+
85
+ # Validate input file exists
86
+ image_path: Path = Path(args.image_path)
87
+ if not image_path.exists():
88
+ logger.error(f"Input file not found: {args.image_path}")
89
+ return 1
90
+
91
+ try:
92
+ target_bytes: int = parse_filesize(args.target_size)
93
+ except ValueError as e:
94
+ logger.error(f"Error: {e}")
95
+ return 1
96
+
97
+ try:
98
+ output_path: str = resize_to_target_filesize(
99
+ args.image_path,
100
+ target_bytes,
101
+ args.output,
102
+ args.format,
103
+ args.min_dimension,
104
+ exact_size=not args.no_exact,
105
+ quiet=args.quiet,
106
+ )
107
+
108
+ logger.debug(f"Successfully processed image: {output_path}")
109
+ return 0
110
+ except KeyboardInterrupt:
111
+ logger.warning("Process interrupted by user.")
112
+ return 130
113
+ except Exception as e:
114
+ logger.error(f"Error: {str(e)}")
115
+ if args.debug:
116
+ logger.exception("Detailed error information:")
117
+ return 1
118
+
119
+
120
+ if __name__ == "__main__":
121
+ sys.exit(main())