imgbytesizer 0.1.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.
- imgbytesizer-0.1.0/LICENSE +21 -0
- imgbytesizer-0.1.0/PKG-INFO +156 -0
- imgbytesizer-0.1.0/README.md +142 -0
- imgbytesizer-0.1.0/imgbytesizer/__init__.py +5 -0
- imgbytesizer-0.1.0/imgbytesizer/formatter.py +110 -0
- imgbytesizer-0.1.0/imgbytesizer/main.py +66 -0
- imgbytesizer-0.1.0/imgbytesizer/resizer.py +306 -0
- imgbytesizer-0.1.0/imgbytesizer/utils.py +39 -0
- imgbytesizer-0.1.0/imgbytesizer.egg-info/PKG-INFO +156 -0
- imgbytesizer-0.1.0/imgbytesizer.egg-info/SOURCES.txt +15 -0
- imgbytesizer-0.1.0/imgbytesizer.egg-info/dependency_links.txt +1 -0
- imgbytesizer-0.1.0/imgbytesizer.egg-info/entry_points.txt +2 -0
- imgbytesizer-0.1.0/imgbytesizer.egg-info/requires.txt +2 -0
- imgbytesizer-0.1.0/imgbytesizer.egg-info/top_level.txt +1 -0
- imgbytesizer-0.1.0/pyproject.toml +16 -0
- imgbytesizer-0.1.0/setup.cfg +7 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-Present Pongsakorn Thipayanate
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: imgbytesizer
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A CLI tool to resize images to a target file size.
|
|
5
|
+
Author-email: pyyupsk <contact@fasu.dev>
|
|
6
|
+
License: MIT License
|
|
7
|
+
Keywords: image,resize,compression,cli,optimize
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: Pillow>=11.0.0
|
|
12
|
+
Requires-Dist: tabulate>=0.9.0
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# ImgByteSizer
|
|
16
|
+
|
|
17
|
+
[](https://pypi.org/project/imgbytesizer/)
|
|
18
|
+
[](https://pepy.tech/projects/imgbytesizer)
|
|
19
|
+
|
|
20
|
+
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
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- 🎯 Resize images to an exact target file size
|
|
25
|
+
- 🖼️ Maintains aspect ratio during resizing
|
|
26
|
+
- 🔍 Intelligent quality optimization with binary search
|
|
27
|
+
- 🔄 Format conversion (JPEG, PNG, WebP)
|
|
28
|
+
- 📏 Minimum dimension constraints
|
|
29
|
+
- 🎨 Beautiful terminal output with progress indicators
|
|
30
|
+
- 📊 Detailed comparison of original vs. processed images
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install imgbytesizer
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Usage
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
imgbytesizer image.jpg 500KB
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Basic Examples
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
# Resize an image to 500KB
|
|
48
|
+
imgbytesizer large_photo.jpg 500KB
|
|
49
|
+
|
|
50
|
+
# Resize and convert to WebP format
|
|
51
|
+
imgbytesizer image.png 250KB -f webp
|
|
52
|
+
|
|
53
|
+
# Specify output file path
|
|
54
|
+
imgbytesizer photo.jpg 1MB -o compressed_photo.jpg
|
|
55
|
+
|
|
56
|
+
# Ensure minimum dimension is at least 400px
|
|
57
|
+
imgbytesizer large_image.jpg 300KB --min-dimension 400
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Command-Line Options
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
usage: imgbytesizer [-h] [-o OUTPUT] [-f FORMAT] [--min-dimension MIN_DIMENSION] [--no-exact] image_path target_size
|
|
64
|
+
|
|
65
|
+
Resize an image to match a target file size
|
|
66
|
+
|
|
67
|
+
positional arguments:
|
|
68
|
+
image_path Path to the input image
|
|
69
|
+
target_size Target file size (e.g., "1MB", "500KB")
|
|
70
|
+
|
|
71
|
+
options:
|
|
72
|
+
-h, --help show this help message and exit
|
|
73
|
+
-o, --output OUTPUT Output path (default: input_resized.ext)
|
|
74
|
+
-f, --format FORMAT Output format (jpg, png, webp)
|
|
75
|
+
--min-dimension MIN_DIMENSION
|
|
76
|
+
Minimum width/height in pixels
|
|
77
|
+
--no-exact Do not pad file to get exact target size
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## How It Works
|
|
81
|
+
|
|
82
|
+
ImgByteSizer uses binary search algorithms to efficiently find the optimal combination of image dimensions and compression quality to match your target file size:
|
|
83
|
+
|
|
84
|
+
1. First attempts to adjust quality without resizing (for formats that support quality settings)
|
|
85
|
+
2. If quality adjustment alone isn't sufficient, performs binary search for optimal dimensions
|
|
86
|
+
3. Fine-tunes with an additional quality optimization pass
|
|
87
|
+
4. Adds minimal padding if necessary to hit the exact target size
|
|
88
|
+
|
|
89
|
+
The tool prioritizes maintaining the highest possible quality while meeting the target size constraint.
|
|
90
|
+
|
|
91
|
+
## Example Output
|
|
92
|
+
|
|
93
|
+
```
|
|
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
|
+
|
|
101
|
+
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
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Real Use Cases
|
|
120
|
+
|
|
121
|
+
### Web Development
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
# Create images that won't exceed page weight budget
|
|
125
|
+
imgbytesizer hero.jpg 200KB --min-dimension 1200
|
|
126
|
+
imgbytesizer background.png 100KB -f webp
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Email Attachments
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
# Shrink images to fit email attachment limits
|
|
133
|
+
imgbytesizer family_photo.jpg 5MB
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Social Media Uploads
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
# Optimize images for social media platforms with size limits
|
|
140
|
+
imgbytesizer profile_pic.jpg 400KB --min-dimension 400
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Requirements
|
|
144
|
+
|
|
145
|
+
- Python 3.9+
|
|
146
|
+
- Dependencies:
|
|
147
|
+
- Pillow >= 11.0.0
|
|
148
|
+
- tabulate >= 0.9.0
|
|
149
|
+
|
|
150
|
+
## Contributing
|
|
151
|
+
|
|
152
|
+
Contributions are welcome! Feel free to submit issues or pull requests.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# ImgByteSizer
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/imgbytesizer/)
|
|
4
|
+
[](https://pepy.tech/projects/imgbytesizer)
|
|
5
|
+
|
|
6
|
+
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
|
+
## Features
|
|
9
|
+
|
|
10
|
+
- 🎯 Resize images to an exact target file size
|
|
11
|
+
- 🖼️ Maintains aspect ratio during resizing
|
|
12
|
+
- 🔍 Intelligent quality optimization with binary search
|
|
13
|
+
- 🔄 Format conversion (JPEG, PNG, WebP)
|
|
14
|
+
- 📏 Minimum dimension constraints
|
|
15
|
+
- 🎨 Beautiful terminal output with progress indicators
|
|
16
|
+
- 📊 Detailed comparison of original vs. processed images
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install imgbytesizer
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
imgbytesizer image.jpg 500KB
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Basic Examples
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# Resize an image to 500KB
|
|
34
|
+
imgbytesizer large_photo.jpg 500KB
|
|
35
|
+
|
|
36
|
+
# Resize and convert to WebP format
|
|
37
|
+
imgbytesizer image.png 250KB -f webp
|
|
38
|
+
|
|
39
|
+
# Specify output file path
|
|
40
|
+
imgbytesizer photo.jpg 1MB -o compressed_photo.jpg
|
|
41
|
+
|
|
42
|
+
# Ensure minimum dimension is at least 400px
|
|
43
|
+
imgbytesizer large_image.jpg 300KB --min-dimension 400
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Command-Line Options
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
usage: imgbytesizer [-h] [-o OUTPUT] [-f FORMAT] [--min-dimension MIN_DIMENSION] [--no-exact] image_path target_size
|
|
50
|
+
|
|
51
|
+
Resize an image to match a target file size
|
|
52
|
+
|
|
53
|
+
positional arguments:
|
|
54
|
+
image_path Path to the input image
|
|
55
|
+
target_size Target file size (e.g., "1MB", "500KB")
|
|
56
|
+
|
|
57
|
+
options:
|
|
58
|
+
-h, --help show this help message and exit
|
|
59
|
+
-o, --output OUTPUT Output path (default: input_resized.ext)
|
|
60
|
+
-f, --format FORMAT Output format (jpg, png, webp)
|
|
61
|
+
--min-dimension MIN_DIMENSION
|
|
62
|
+
Minimum width/height in pixels
|
|
63
|
+
--no-exact Do not pad file to get exact target size
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## How It Works
|
|
67
|
+
|
|
68
|
+
ImgByteSizer uses binary search algorithms to efficiently find the optimal combination of image dimensions and compression quality to match your target file size:
|
|
69
|
+
|
|
70
|
+
1. First attempts to adjust quality without resizing (for formats that support quality settings)
|
|
71
|
+
2. If quality adjustment alone isn't sufficient, performs binary search for optimal dimensions
|
|
72
|
+
3. Fine-tunes with an additional quality optimization pass
|
|
73
|
+
4. Adds minimal padding if necessary to hit the exact target size
|
|
74
|
+
|
|
75
|
+
The tool prioritizes maintaining the highest possible quality while meeting the target size constraint.
|
|
76
|
+
|
|
77
|
+
## Example Output
|
|
78
|
+
|
|
79
|
+
```
|
|
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
|
+
|
|
87
|
+
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
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Real Use Cases
|
|
106
|
+
|
|
107
|
+
### Web Development
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
# Create images that won't exceed page weight budget
|
|
111
|
+
imgbytesizer hero.jpg 200KB --min-dimension 1200
|
|
112
|
+
imgbytesizer background.png 100KB -f webp
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Email Attachments
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
# Shrink images to fit email attachment limits
|
|
119
|
+
imgbytesizer family_photo.jpg 5MB
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Social Media Uploads
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
# Optimize images for social media platforms with size limits
|
|
126
|
+
imgbytesizer profile_pic.jpg 400KB --min-dimension 400
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Requirements
|
|
130
|
+
|
|
131
|
+
- Python 3.9+
|
|
132
|
+
- Dependencies:
|
|
133
|
+
- Pillow >= 11.0.0
|
|
134
|
+
- tabulate >= 0.9.0
|
|
135
|
+
|
|
136
|
+
## Contributing
|
|
137
|
+
|
|
138
|
+
Contributions are welcome! Feel free to submit issues or pull requests.
|
|
139
|
+
|
|
140
|
+
## License
|
|
141
|
+
|
|
142
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Terminal formatting utilities for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
import shutil
|
|
5
|
+
from tabulate import tabulate
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# ANSI Color Codes for beautiful terminal output
|
|
9
|
+
class Colors:
|
|
10
|
+
HEADER = '\033[95m'
|
|
11
|
+
BLUE = '\033[94m'
|
|
12
|
+
CYAN = '\033[96m'
|
|
13
|
+
GREEN = '\033[92m'
|
|
14
|
+
YELLOW = '\033[93m'
|
|
15
|
+
RED = '\033[91m'
|
|
16
|
+
ENDC = '\033[0m'
|
|
17
|
+
BOLD = '\033[1m'
|
|
18
|
+
UNDERLINE = '\033[4m'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_terminal_width():
|
|
22
|
+
"""Get the width of the terminal."""
|
|
23
|
+
try:
|
|
24
|
+
columns = shutil.get_terminal_size().columns
|
|
25
|
+
return max(80, columns)
|
|
26
|
+
except Exception:
|
|
27
|
+
return 80
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def format_filesize(size_bytes):
|
|
31
|
+
"""Format file size in a human-readable format."""
|
|
32
|
+
if size_bytes < 1024:
|
|
33
|
+
return f"{size_bytes} B"
|
|
34
|
+
elif size_bytes < 1024 * 1024:
|
|
35
|
+
return f"{size_bytes/1024} KB"
|
|
36
|
+
else:
|
|
37
|
+
return f"{size_bytes/(1024*1024)} MB"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def print_progress_bar(progress, total, prefix='', suffix='', length=30):
|
|
41
|
+
"""Print a progress bar with percentage."""
|
|
42
|
+
percent = min(100, int(100.0 * progress / total))
|
|
43
|
+
filled_length = int(length * progress // total)
|
|
44
|
+
bar = '█' * filled_length + '░' * (length - filled_length)
|
|
45
|
+
print(f"\r{prefix} |{Colors.GREEN}{bar}{Colors.ENDC}| {percent}% {suffix}", end='\r')
|
|
46
|
+
if progress == total:
|
|
47
|
+
print()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def print_result(name, value, status=None):
|
|
51
|
+
"""Print a name-value pair with optional status color."""
|
|
52
|
+
value_color = Colors.ENDC
|
|
53
|
+
if status == 'good':
|
|
54
|
+
value_color = Colors.GREEN
|
|
55
|
+
elif status == 'warning':
|
|
56
|
+
value_color = Colors.YELLOW
|
|
57
|
+
elif status == 'bad':
|
|
58
|
+
value_color = Colors.RED
|
|
59
|
+
|
|
60
|
+
print(f" {Colors.BOLD}{name}:{Colors.ENDC} {value_color}{value}{Colors.ENDC}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def print_processing_step(step, description):
|
|
64
|
+
"""Print a processing step with a spinner."""
|
|
65
|
+
spinner = ["◐", "◓", "◑", "◒"]
|
|
66
|
+
print(f"{Colors.BLUE}{spinner[step % len(spinner)]}{Colors.ENDC} {description}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def print_comparison_table(original_size, original_dimensions,
|
|
70
|
+
final_size, final_dimensions, target_size):
|
|
71
|
+
|
|
72
|
+
orig_dim = f"{original_dimensions[0]}×{original_dimensions[1]}"
|
|
73
|
+
new_dim = f"{final_dimensions[0]}×{final_dimensions[1]}"
|
|
74
|
+
orig_size = format_filesize(original_size)
|
|
75
|
+
new_size = format_filesize(final_size)
|
|
76
|
+
target = format_filesize(target_size)
|
|
77
|
+
diff = abs(final_size - target_size)
|
|
78
|
+
diff_pct = (diff / target_size) * 100
|
|
79
|
+
reduction = ((original_size - final_size) / original_size) * \
|
|
80
|
+
100 if original_size > final_size else 0
|
|
81
|
+
|
|
82
|
+
# Determine color based on how close to target
|
|
83
|
+
if diff_pct < 1:
|
|
84
|
+
diff_color = Colors.GREEN
|
|
85
|
+
elif diff_pct < 5:
|
|
86
|
+
diff_color = Colors.YELLOW
|
|
87
|
+
else:
|
|
88
|
+
diff_color = Colors.RED
|
|
89
|
+
|
|
90
|
+
table = [
|
|
91
|
+
[f"{Colors.BOLD}Dimensions{Colors.ENDC}", f"{Colors.CYAN}{orig_dim}{Colors.ENDC}",
|
|
92
|
+
f"{Colors.GREEN}{new_dim}{Colors.ENDC}"],
|
|
93
|
+
[f"{Colors.BOLD}Size{Colors.ENDC}", f"{Colors.CYAN}{orig_size}{Colors.ENDC}",
|
|
94
|
+
f"{Colors.GREEN}{new_size}{Colors.ENDC}"],
|
|
95
|
+
[f"{Colors.BOLD}Target Size{Colors.ENDC}", "", f"{Colors.BLUE}{target}{Colors.ENDC}"],
|
|
96
|
+
[f"{Colors.BOLD}Difference{Colors.ENDC}", "",
|
|
97
|
+
f"{diff_color}{format_filesize(diff)} ({diff_pct:.1f}%){Colors.ENDC}"],
|
|
98
|
+
[f"{Colors.BOLD}Reduction{Colors.ENDC}", "",
|
|
99
|
+
f"{Colors.CYAN}{reduction:.1f}% smaller{Colors.ENDC}"
|
|
100
|
+
if reduction else f"{Colors.YELLOW}N/A{Colors.ENDC}"]
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
print()
|
|
104
|
+
print(
|
|
105
|
+
tabulate(table, headers=[
|
|
106
|
+
f"{Colors.UNDERLINE}Metric{Colors.ENDC}",
|
|
107
|
+
f"{Colors.UNDERLINE}Original{Colors.ENDC}",
|
|
108
|
+
f"{Colors.UNDERLINE}Processed{Colors.ENDC}"
|
|
109
|
+
], tablefmt="rounded_grid")
|
|
110
|
+
)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command-line interface for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
import sys
|
|
5
|
+
import argparse
|
|
6
|
+
|
|
7
|
+
from .formatter import Colors
|
|
8
|
+
from .resizer import resize_to_target_filesize
|
|
9
|
+
from .utils import parse_filesize
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
"""Main entry point for the CLI."""
|
|
14
|
+
parser = argparse.ArgumentParser(
|
|
15
|
+
description='Resize an image to match a target file size',
|
|
16
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
17
|
+
epilog="""
|
|
18
|
+
Examples:
|
|
19
|
+
%(prog)s image.jpg 500KB # Resize to 500 KB
|
|
20
|
+
%(prog)s photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
|
|
21
|
+
%(prog)s image.jpg 100KB -f webp # Resize and convert to WebP
|
|
22
|
+
%(prog)s large.jpg 50KB --min-dimension 200 # Ensure min dimension is 200px
|
|
23
|
+
"""
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
parser.add_argument('image_path', help='Path to the input image')
|
|
27
|
+
parser.add_argument('target_size', help='Target file size (e.g., "1MB", "500KB")')
|
|
28
|
+
parser.add_argument('-o', '--output', help='Output path (default: input_resized.ext)')
|
|
29
|
+
parser.add_argument('-f', '--format', help='Output format (jpg, png, webp)')
|
|
30
|
+
parser.add_argument('--min-dimension', type=int, help='Minimum width/height in pixels')
|
|
31
|
+
parser.add_argument('--no-exact', action='store_true',
|
|
32
|
+
help='Do not pad file to get exact target size')
|
|
33
|
+
|
|
34
|
+
# Handle no arguments case with nice help
|
|
35
|
+
if len(sys.argv) == 1:
|
|
36
|
+
parser.print_help()
|
|
37
|
+
return 0
|
|
38
|
+
|
|
39
|
+
args = parser.parse_args()
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
target_bytes = parse_filesize(args.target_size)
|
|
43
|
+
except ValueError as e:
|
|
44
|
+
print(f"{Colors.RED}{Colors.BOLD}Error: {e}{Colors.ENDC}")
|
|
45
|
+
return 1
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
resize_to_target_filesize(
|
|
49
|
+
args.image_path,
|
|
50
|
+
target_bytes,
|
|
51
|
+
args.output,
|
|
52
|
+
args.format,
|
|
53
|
+
args.min_dimension,
|
|
54
|
+
exact_size=not args.no_exact
|
|
55
|
+
)
|
|
56
|
+
return 0
|
|
57
|
+
except KeyboardInterrupt:
|
|
58
|
+
print(f"\n\n{Colors.YELLOW}Process interrupted by user.{Colors.ENDC}")
|
|
59
|
+
return 130
|
|
60
|
+
except Exception as e:
|
|
61
|
+
print(f"\n{Colors.RED}{Colors.BOLD}Error: {e}{Colors.ENDC}")
|
|
62
|
+
return 1
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
if __name__ == "__main__":
|
|
66
|
+
sys.exit(main())
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core image resizing functionality.
|
|
3
|
+
"""
|
|
4
|
+
import os
|
|
5
|
+
import io
|
|
6
|
+
import time
|
|
7
|
+
from PIL import Image
|
|
8
|
+
|
|
9
|
+
from .formatter import (
|
|
10
|
+
Colors, print_progress_bar, print_result, print_processing_step,
|
|
11
|
+
print_comparison_table, format_filesize
|
|
12
|
+
)
|
|
13
|
+
from .utils import get_file_size_bytes
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def resize_to_target_filesize(
|
|
17
|
+
image_path, target_size_bytes, output_path=None,
|
|
18
|
+
format=None, min_dimension=None, exact_size=True
|
|
19
|
+
):
|
|
20
|
+
"""Resize an image to match a target file size in bytes."""
|
|
21
|
+
start_time = time.time()
|
|
22
|
+
|
|
23
|
+
# Load the image and get original info
|
|
24
|
+
print_processing_step(0, f"Opening {Colors.YELLOW}{os.path.basename(image_path)}{Colors.ENDC}")
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
img = Image.open(image_path)
|
|
28
|
+
except Exception as e:
|
|
29
|
+
print(f"\n{Colors.RED}{Colors.BOLD}ERROR: Could not open image: {e}{Colors.ENDC}")
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
orig_width, orig_height = img.size
|
|
33
|
+
aspect_ratio = orig_width / orig_height
|
|
34
|
+
|
|
35
|
+
# Determine format
|
|
36
|
+
if format is None:
|
|
37
|
+
format = img.format
|
|
38
|
+
|
|
39
|
+
pil_format = format.upper() if format else img.format
|
|
40
|
+
if pil_format == 'JPG':
|
|
41
|
+
pil_format = 'JPEG'
|
|
42
|
+
|
|
43
|
+
# Determine output path
|
|
44
|
+
if output_path is None:
|
|
45
|
+
base_name, _ = os.path.splitext(image_path)
|
|
46
|
+
output_path = f"{base_name}_resized.{pil_format.lower()}"
|
|
47
|
+
|
|
48
|
+
# Print image information
|
|
49
|
+
print_result("File", os.path.basename(image_path))
|
|
50
|
+
print_result("Format", pil_format)
|
|
51
|
+
print_result("Dimensions", f"{orig_width} × {orig_height} pixels")
|
|
52
|
+
|
|
53
|
+
orig_size, _ = get_file_size_bytes(img, pil_format)
|
|
54
|
+
print_result("Size", format_filesize(orig_size))
|
|
55
|
+
print_result("Target size", format_filesize(target_size_bytes))
|
|
56
|
+
|
|
57
|
+
# Check if resizing is needed
|
|
58
|
+
if orig_size <= target_size_bytes:
|
|
59
|
+
|
|
60
|
+
print(f"{Colors.GREEN}✓ Original image is already smaller than target size{Colors.ENDC}")
|
|
61
|
+
img.save(output_path)
|
|
62
|
+
|
|
63
|
+
print_result("Status", "No resizing needed", "good")
|
|
64
|
+
print_result("Output", os.path.basename(output_path))
|
|
65
|
+
return output_path
|
|
66
|
+
|
|
67
|
+
# Try quality adjustment first for formats that support it
|
|
68
|
+
if pil_format in ['JPEG', 'WEBP']:
|
|
69
|
+
|
|
70
|
+
print("Trying quality adjustment without resizing...")
|
|
71
|
+
|
|
72
|
+
low, high = 1, 95
|
|
73
|
+
best_quality = None
|
|
74
|
+
best_size = None
|
|
75
|
+
best_buffer = None
|
|
76
|
+
iteration = 0
|
|
77
|
+
total_iterations = min(10, high - low) # Estimate iterations for progress bar
|
|
78
|
+
|
|
79
|
+
while low <= high:
|
|
80
|
+
iteration += 1
|
|
81
|
+
mid = (low + high) // 2
|
|
82
|
+
size, buffer = get_file_size_bytes(img, pil_format, mid)
|
|
83
|
+
|
|
84
|
+
print_progress_bar(iteration, total_iterations,
|
|
85
|
+
prefix=f"Testing quality {mid:2d}",
|
|
86
|
+
suffix=f"Size: {format_filesize(size)}")
|
|
87
|
+
|
|
88
|
+
if size <= target_size_bytes and (best_size is None or size > best_size):
|
|
89
|
+
best_quality = mid
|
|
90
|
+
best_size = size
|
|
91
|
+
best_buffer = buffer
|
|
92
|
+
|
|
93
|
+
if size > target_size_bytes:
|
|
94
|
+
high = mid - 1
|
|
95
|
+
else:
|
|
96
|
+
low = mid + 1
|
|
97
|
+
|
|
98
|
+
# Add small delay for visual effect in progress bar
|
|
99
|
+
time.sleep(0.01)
|
|
100
|
+
|
|
101
|
+
if best_size is not None:
|
|
102
|
+
print(
|
|
103
|
+
f"\n{Colors.GREEN}✓ Found optimal quality: {best_quality} "
|
|
104
|
+
f"(size: {format_filesize(best_size)}){Colors.ENDC}"
|
|
105
|
+
)
|
|
106
|
+
with open(output_path, 'wb') as f:
|
|
107
|
+
f.write(best_buffer.getvalue())
|
|
108
|
+
|
|
109
|
+
# Final report
|
|
110
|
+
final_img = Image.open(output_path)
|
|
111
|
+
final_width, final_height = final_img.size
|
|
112
|
+
final_size = os.path.getsize(output_path)
|
|
113
|
+
|
|
114
|
+
print_comparison_table(orig_size, (orig_width, orig_height),
|
|
115
|
+
final_size, (final_width, final_height),
|
|
116
|
+
target_size_bytes)
|
|
117
|
+
|
|
118
|
+
elapsed = time.time() - start_time
|
|
119
|
+
print_result("Time taken", f"{elapsed:.2f} seconds")
|
|
120
|
+
print_result(
|
|
121
|
+
"Output file", f"{Colors.UNDERLINE}{os.path.basename(output_path)}{Colors.ENDC}")
|
|
122
|
+
|
|
123
|
+
return output_path
|
|
124
|
+
|
|
125
|
+
# If quality adjustment didn't work, try resizing
|
|
126
|
+
print("Performing size-based optimization...")
|
|
127
|
+
|
|
128
|
+
low_scale = 0.01
|
|
129
|
+
high_scale = 1.0
|
|
130
|
+
best_size = None
|
|
131
|
+
best_buffer = None
|
|
132
|
+
iterations = 0
|
|
133
|
+
max_iterations = 10 # Limit iterations for binary search visualization
|
|
134
|
+
|
|
135
|
+
while high_scale - low_scale > 0.01 and iterations < max_iterations:
|
|
136
|
+
iterations += 1
|
|
137
|
+
mid_scale = (low_scale + high_scale) / 2
|
|
138
|
+
new_width = int(orig_width * mid_scale)
|
|
139
|
+
new_height = int(orig_height * mid_scale)
|
|
140
|
+
|
|
141
|
+
if min_dimension is not None:
|
|
142
|
+
if new_width < min_dimension or new_height < min_dimension:
|
|
143
|
+
scale_w = min_dimension / new_width if new_width < min_dimension else 1
|
|
144
|
+
scale_h = min_dimension / new_height if new_height < min_dimension else 1
|
|
145
|
+
scale = max(scale_w, scale_h)
|
|
146
|
+
new_width = max(min_dimension, int(new_width * scale))
|
|
147
|
+
new_height = max(min_dimension, int(new_height * scale))
|
|
148
|
+
|
|
149
|
+
print_processing_step(
|
|
150
|
+
iterations, f"Trying scale {mid_scale:.2f} ({new_width}×{new_height})")
|
|
151
|
+
resized_img = img.resize((new_width, new_height), Image.LANCZOS)
|
|
152
|
+
|
|
153
|
+
if pil_format in ['JPEG', 'WEBP']:
|
|
154
|
+
# For quality-supporting formats, do a nested binary search for quality
|
|
155
|
+
quality_low, quality_high = 1, 95
|
|
156
|
+
best_q = None
|
|
157
|
+
best_q_size = None
|
|
158
|
+
best_q_buffer = None
|
|
159
|
+
q_iterations = 0
|
|
160
|
+
|
|
161
|
+
print(f" {Colors.CYAN}Finding optimal quality...{Colors.ENDC}")
|
|
162
|
+
|
|
163
|
+
while quality_low <= quality_high and q_iterations < 8: # Limit inner search as well
|
|
164
|
+
q_iterations += 1
|
|
165
|
+
q_mid = (quality_low + quality_high) // 2
|
|
166
|
+
q_size, q_buffer = get_file_size_bytes(resized_img, pil_format, q_mid)
|
|
167
|
+
|
|
168
|
+
result_indicator = " "
|
|
169
|
+
if q_size <= target_size_bytes:
|
|
170
|
+
result_indicator = f"{Colors.GREEN}✓{Colors.ENDC}"
|
|
171
|
+
if best_q_size is None or q_size > best_q_size:
|
|
172
|
+
best_q = q_mid
|
|
173
|
+
best_q_size = q_size
|
|
174
|
+
best_q_buffer = q_buffer
|
|
175
|
+
else:
|
|
176
|
+
result_indicator = f"{Colors.RED}✗{Colors.ENDC}"
|
|
177
|
+
|
|
178
|
+
print(f" {result_indicator} Quality {q_mid:2d}: {format_filesize(q_size)}")
|
|
179
|
+
|
|
180
|
+
if q_size > target_size_bytes:
|
|
181
|
+
quality_high = q_mid - 1
|
|
182
|
+
else:
|
|
183
|
+
quality_low = q_mid + 1
|
|
184
|
+
|
|
185
|
+
time.sleep(0.01) # Small delay for visual effect
|
|
186
|
+
|
|
187
|
+
if best_q_size is not None:
|
|
188
|
+
size, buffer = best_q_size, best_q_buffer
|
|
189
|
+
print(f" {Colors.GREEN}→ Best quality: {best_q}{Colors.ENDC}")
|
|
190
|
+
else:
|
|
191
|
+
size, buffer = get_file_size_bytes(resized_img, pil_format, 1)
|
|
192
|
+
print(f" {Colors.YELLOW}→ Using minimum quality: 1{Colors.ENDC}")
|
|
193
|
+
else:
|
|
194
|
+
size, buffer = get_file_size_bytes(resized_img, pil_format)
|
|
195
|
+
|
|
196
|
+
result_status = "✓" if size <= target_size_bytes else "✗"
|
|
197
|
+
result_color = Colors.GREEN if size <= target_size_bytes else Colors.RED
|
|
198
|
+
print(f" {result_color}{result_status} Result: {format_filesize(size)}{Colors.ENDC}")
|
|
199
|
+
|
|
200
|
+
if size <= target_size_bytes and (best_size is None or size > best_size):
|
|
201
|
+
best_size = size
|
|
202
|
+
best_buffer = buffer
|
|
203
|
+
|
|
204
|
+
if size > target_size_bytes:
|
|
205
|
+
high_scale = mid_scale
|
|
206
|
+
else:
|
|
207
|
+
low_scale = mid_scale
|
|
208
|
+
|
|
209
|
+
# If no suitable size was found
|
|
210
|
+
if best_buffer is None:
|
|
211
|
+
print(
|
|
212
|
+
f"\n{Colors.YELLOW}⚠ Could not find optimal size. "
|
|
213
|
+
f"Creating smallest possible image...{Colors.ENDC}"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
if min_dimension:
|
|
217
|
+
if orig_width > orig_height:
|
|
218
|
+
new_width = int(min_dimension * aspect_ratio)
|
|
219
|
+
new_height = min_dimension
|
|
220
|
+
else:
|
|
221
|
+
new_width = min_dimension
|
|
222
|
+
new_height = int(min_dimension / aspect_ratio)
|
|
223
|
+
else:
|
|
224
|
+
new_width = max(1, int(orig_width * 0.01))
|
|
225
|
+
new_height = max(1, int(orig_height * 0.01))
|
|
226
|
+
|
|
227
|
+
resized_img = img.resize((new_width, new_height), Image.LANCZOS)
|
|
228
|
+
quality = 1 if pil_format in ['JPEG', 'WEBP'] else None
|
|
229
|
+
best_size, best_buffer = get_file_size_bytes(resized_img, pil_format, quality)
|
|
230
|
+
|
|
231
|
+
print(f" Created {new_width}×{new_height} image with size {format_filesize(best_size)}")
|
|
232
|
+
|
|
233
|
+
# Save the best result
|
|
234
|
+
with open(output_path, 'wb') as f:
|
|
235
|
+
f.write(best_buffer.getvalue())
|
|
236
|
+
|
|
237
|
+
final_img = Image.open(output_path)
|
|
238
|
+
final_width, final_height = final_img.size
|
|
239
|
+
final_size = os.path.getsize(output_path)
|
|
240
|
+
|
|
241
|
+
# Fine-tuning to match exact target size if needed
|
|
242
|
+
if exact_size and final_size < target_size_bytes:
|
|
243
|
+
|
|
244
|
+
print("Adjusting to exact target size...")
|
|
245
|
+
|
|
246
|
+
if pil_format in ['JPEG', 'WEBP'] and abs(final_size - target_size_bytes) > 100:
|
|
247
|
+
print("Optimizing quality for exact size match...")
|
|
248
|
+
best_quality = None
|
|
249
|
+
best_size_diff = abs(final_size - target_size_bytes)
|
|
250
|
+
|
|
251
|
+
quality_range = range(1, 101, 5) # Test fewer qualities for speed
|
|
252
|
+
for i, quality in enumerate(quality_range):
|
|
253
|
+
print_progress_bar(
|
|
254
|
+
i+1, len(quality_range),
|
|
255
|
+
prefix=f"Testing quality {quality:3d}",
|
|
256
|
+
suffix=""
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
test_buffer = io.BytesIO()
|
|
260
|
+
final_img.save(test_buffer, format=pil_format, quality=quality)
|
|
261
|
+
test_size = test_buffer.tell()
|
|
262
|
+
size_diff = abs(test_size - target_size_bytes)
|
|
263
|
+
|
|
264
|
+
if size_diff < best_size_diff:
|
|
265
|
+
best_quality = quality
|
|
266
|
+
best_size_diff = size_diff
|
|
267
|
+
|
|
268
|
+
time.sleep(0.01) # Visual delay
|
|
269
|
+
|
|
270
|
+
if best_quality is not None:
|
|
271
|
+
final_img.save(output_path, format=pil_format, quality=best_quality)
|
|
272
|
+
final_size = os.path.getsize(output_path)
|
|
273
|
+
print(
|
|
274
|
+
f"\n{Colors.GREEN}✓ Quality adjusted to {best_quality}: "
|
|
275
|
+
f"{format_filesize(final_size)}{Colors.ENDC}"
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
# If we still need to pad the file
|
|
279
|
+
if final_size < target_size_bytes:
|
|
280
|
+
bytes_needed = target_size_bytes - final_size
|
|
281
|
+
print(f"Adding {format_filesize(bytes_needed)} padding...")
|
|
282
|
+
|
|
283
|
+
if pil_format == 'JPEG':
|
|
284
|
+
comment = b'X' * bytes_needed
|
|
285
|
+
temp_buffer = io.BytesIO()
|
|
286
|
+
final_img.save(temp_buffer, format='JPEG', quality=95,
|
|
287
|
+
comment=comment.decode('latin1', errors='replace'))
|
|
288
|
+
with open(output_path, 'wb') as f:
|
|
289
|
+
f.write(temp_buffer.getvalue())
|
|
290
|
+
else:
|
|
291
|
+
with open(output_path, 'ab') as f:
|
|
292
|
+
f.write(b'P' * bytes_needed)
|
|
293
|
+
|
|
294
|
+
final_size = os.path.getsize(output_path)
|
|
295
|
+
print(f"{Colors.GREEN}✓ File padded to exact size{Colors.ENDC}")
|
|
296
|
+
|
|
297
|
+
# Final report
|
|
298
|
+
print_comparison_table(orig_size, (orig_width, orig_height),
|
|
299
|
+
final_size, (final_width, final_height),
|
|
300
|
+
target_size_bytes)
|
|
301
|
+
|
|
302
|
+
elapsed = time.time() - start_time
|
|
303
|
+
print_result("Time taken", f"{elapsed:.2f} seconds")
|
|
304
|
+
print_result("Output file", f"{Colors.UNDERLINE}{os.path.basename(output_path)}{Colors.ENDC}")
|
|
305
|
+
|
|
306
|
+
return output_path
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utility functions for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
import io
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def parse_filesize(size_str):
|
|
8
|
+
"""Parse a file size string like '1MB' to bytes."""
|
|
9
|
+
size_str = size_str.strip().upper()
|
|
10
|
+
if size_str.endswith('KB'):
|
|
11
|
+
return int(float(size_str[:-2]) * 1024)
|
|
12
|
+
elif size_str.endswith('MB'):
|
|
13
|
+
return int(float(size_str[:-2]) * 1024 * 1024)
|
|
14
|
+
elif size_str.endswith('GB'):
|
|
15
|
+
return int(float(size_str[:-2]) * 1024 * 1024 * 1024)
|
|
16
|
+
elif size_str.endswith('B'):
|
|
17
|
+
return int(size_str[:-1])
|
|
18
|
+
else:
|
|
19
|
+
try:
|
|
20
|
+
return int(size_str)
|
|
21
|
+
except ValueError:
|
|
22
|
+
raise ValueError("Invalid file size format. Use B, KB, MB, or GB suffix.")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_file_size_bytes(img, format, quality=None):
|
|
26
|
+
"""Get the file size in bytes for an image with the specified format and quality."""
|
|
27
|
+
out_buffer = io.BytesIO()
|
|
28
|
+
save_args = {'format': format}
|
|
29
|
+
if quality is not None:
|
|
30
|
+
if format == 'JPEG':
|
|
31
|
+
save_args['quality'] = quality
|
|
32
|
+
elif format == 'PNG':
|
|
33
|
+
save_args['optimize'] = True
|
|
34
|
+
save_args['compress_level'] = quality
|
|
35
|
+
elif format == 'WEBP':
|
|
36
|
+
save_args['quality'] = quality
|
|
37
|
+
|
|
38
|
+
img.save(out_buffer, **save_args)
|
|
39
|
+
return out_buffer.tell(), out_buffer
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: imgbytesizer
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A CLI tool to resize images to a target file size.
|
|
5
|
+
Author-email: pyyupsk <contact@fasu.dev>
|
|
6
|
+
License: MIT License
|
|
7
|
+
Keywords: image,resize,compression,cli,optimize
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: Pillow>=11.0.0
|
|
12
|
+
Requires-Dist: tabulate>=0.9.0
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# ImgByteSizer
|
|
16
|
+
|
|
17
|
+
[](https://pypi.org/project/imgbytesizer/)
|
|
18
|
+
[](https://pepy.tech/projects/imgbytesizer)
|
|
19
|
+
|
|
20
|
+
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
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- 🎯 Resize images to an exact target file size
|
|
25
|
+
- 🖼️ Maintains aspect ratio during resizing
|
|
26
|
+
- 🔍 Intelligent quality optimization with binary search
|
|
27
|
+
- 🔄 Format conversion (JPEG, PNG, WebP)
|
|
28
|
+
- 📏 Minimum dimension constraints
|
|
29
|
+
- 🎨 Beautiful terminal output with progress indicators
|
|
30
|
+
- 📊 Detailed comparison of original vs. processed images
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install imgbytesizer
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Usage
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
imgbytesizer image.jpg 500KB
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Basic Examples
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
# Resize an image to 500KB
|
|
48
|
+
imgbytesizer large_photo.jpg 500KB
|
|
49
|
+
|
|
50
|
+
# Resize and convert to WebP format
|
|
51
|
+
imgbytesizer image.png 250KB -f webp
|
|
52
|
+
|
|
53
|
+
# Specify output file path
|
|
54
|
+
imgbytesizer photo.jpg 1MB -o compressed_photo.jpg
|
|
55
|
+
|
|
56
|
+
# Ensure minimum dimension is at least 400px
|
|
57
|
+
imgbytesizer large_image.jpg 300KB --min-dimension 400
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Command-Line Options
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
usage: imgbytesizer [-h] [-o OUTPUT] [-f FORMAT] [--min-dimension MIN_DIMENSION] [--no-exact] image_path target_size
|
|
64
|
+
|
|
65
|
+
Resize an image to match a target file size
|
|
66
|
+
|
|
67
|
+
positional arguments:
|
|
68
|
+
image_path Path to the input image
|
|
69
|
+
target_size Target file size (e.g., "1MB", "500KB")
|
|
70
|
+
|
|
71
|
+
options:
|
|
72
|
+
-h, --help show this help message and exit
|
|
73
|
+
-o, --output OUTPUT Output path (default: input_resized.ext)
|
|
74
|
+
-f, --format FORMAT Output format (jpg, png, webp)
|
|
75
|
+
--min-dimension MIN_DIMENSION
|
|
76
|
+
Minimum width/height in pixels
|
|
77
|
+
--no-exact Do not pad file to get exact target size
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## How It Works
|
|
81
|
+
|
|
82
|
+
ImgByteSizer uses binary search algorithms to efficiently find the optimal combination of image dimensions and compression quality to match your target file size:
|
|
83
|
+
|
|
84
|
+
1. First attempts to adjust quality without resizing (for formats that support quality settings)
|
|
85
|
+
2. If quality adjustment alone isn't sufficient, performs binary search for optimal dimensions
|
|
86
|
+
3. Fine-tunes with an additional quality optimization pass
|
|
87
|
+
4. Adds minimal padding if necessary to hit the exact target size
|
|
88
|
+
|
|
89
|
+
The tool prioritizes maintaining the highest possible quality while meeting the target size constraint.
|
|
90
|
+
|
|
91
|
+
## Example Output
|
|
92
|
+
|
|
93
|
+
```
|
|
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
|
+
|
|
101
|
+
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
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Real Use Cases
|
|
120
|
+
|
|
121
|
+
### Web Development
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
# Create images that won't exceed page weight budget
|
|
125
|
+
imgbytesizer hero.jpg 200KB --min-dimension 1200
|
|
126
|
+
imgbytesizer background.png 100KB -f webp
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Email Attachments
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
# Shrink images to fit email attachment limits
|
|
133
|
+
imgbytesizer family_photo.jpg 5MB
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Social Media Uploads
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
# Optimize images for social media platforms with size limits
|
|
140
|
+
imgbytesizer profile_pic.jpg 400KB --min-dimension 400
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Requirements
|
|
144
|
+
|
|
145
|
+
- Python 3.9+
|
|
146
|
+
- Dependencies:
|
|
147
|
+
- Pillow >= 11.0.0
|
|
148
|
+
- tabulate >= 0.9.0
|
|
149
|
+
|
|
150
|
+
## Contributing
|
|
151
|
+
|
|
152
|
+
Contributions are welcome! Feel free to submit issues or pull requests.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
setup.cfg
|
|
5
|
+
imgbytesizer/__init__.py
|
|
6
|
+
imgbytesizer/formatter.py
|
|
7
|
+
imgbytesizer/main.py
|
|
8
|
+
imgbytesizer/resizer.py
|
|
9
|
+
imgbytesizer/utils.py
|
|
10
|
+
imgbytesizer.egg-info/PKG-INFO
|
|
11
|
+
imgbytesizer.egg-info/SOURCES.txt
|
|
12
|
+
imgbytesizer.egg-info/dependency_links.txt
|
|
13
|
+
imgbytesizer.egg-info/entry_points.txt
|
|
14
|
+
imgbytesizer.egg-info/requires.txt
|
|
15
|
+
imgbytesizer.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
imgbytesizer
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
authors = [{ name = "pyyupsk", email = "contact@fasu.dev" }]
|
|
3
|
+
description = "A CLI tool to resize images to a target file size."
|
|
4
|
+
dependencies = ["Pillow>=11.0.0", "tabulate>=0.9.0"]
|
|
5
|
+
keywords = ["image", "resize", "compression", "cli", "optimize"]
|
|
6
|
+
license = { text = "MIT License" }
|
|
7
|
+
name = "imgbytesizer"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.9"
|
|
10
|
+
version = "0.1.0"
|
|
11
|
+
|
|
12
|
+
[project.scripts]
|
|
13
|
+
imgbytesizer = "imgbytesizer.main:main"
|
|
14
|
+
|
|
15
|
+
[tool.setuptools]
|
|
16
|
+
packages = ["imgbytesizer"]
|