imagex 0.2.2__tar.gz → 0.4.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.
Files changed (49) hide show
  1. {imagex-0.2.2 → imagex-0.4.0}/PKG-INFO +17 -11
  2. {imagex-0.2.2 → imagex-0.4.0}/README.md +16 -10
  3. imagex-0.4.0/imagex/__init__.py +1 -0
  4. {imagex-0.2.2 → imagex-0.4.0}/imagex/cli.py +59 -32
  5. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/__init__.py +6 -0
  6. imagex-0.4.0/imagex/features/compress.py +237 -0
  7. imagex-0.4.0/imagex/features/grayscale.py +57 -0
  8. imagex-0.4.0/imagex/features/invert.py +30 -0
  9. imagex-0.4.0/imagex/features/to_pdf.py +47 -0
  10. {imagex-0.2.2 → imagex-0.4.0}/imagex/utils/file_ops.py +25 -0
  11. {imagex-0.2.2 → imagex-0.4.0}/imagex/utils/progress.py +24 -1
  12. imagex-0.4.0/imagex/utils/wizard.py +37 -0
  13. {imagex-0.2.2 → imagex-0.4.0}/imagex.egg-info/PKG-INFO +17 -11
  14. {imagex-0.2.2 → imagex-0.4.0}/imagex.egg-info/SOURCES.txt +7 -0
  15. {imagex-0.2.2 → imagex-0.4.0}/pyproject.toml +1 -1
  16. {imagex-0.2.2 → imagex-0.4.0}/tests/test_cli.py +34 -1
  17. imagex-0.4.0/tests/test_compress.py +172 -0
  18. imagex-0.4.0/tests/test_grayscale.py +53 -0
  19. imagex-0.4.0/tests/test_invert.py +57 -0
  20. imagex-0.4.0/tests/test_to_pdf.py +59 -0
  21. imagex-0.2.2/imagex/__init__.py +0 -1
  22. imagex-0.2.2/imagex/features/compress.py +0 -102
  23. imagex-0.2.2/tests/test_compress.py +0 -78
  24. {imagex-0.2.2 → imagex-0.4.0}/LICENSE +0 -0
  25. {imagex-0.2.2 → imagex-0.4.0}/imagex/__main__.py +0 -0
  26. {imagex-0.2.2 → imagex-0.4.0}/imagex/config.py +0 -0
  27. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/add_noise.py +0 -0
  28. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/convert.py +0 -0
  29. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/flip.py +0 -0
  30. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/remove_metadata.py +0 -0
  31. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/rename_batch.py +0 -0
  32. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/resize.py +0 -0
  33. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/rotate.py +0 -0
  34. {imagex-0.2.2 → imagex-0.4.0}/imagex/features/watermark.py +0 -0
  35. {imagex-0.2.2 → imagex-0.4.0}/imagex/utils/__init__.py +0 -0
  36. {imagex-0.2.2 → imagex-0.4.0}/imagex.egg-info/dependency_links.txt +0 -0
  37. {imagex-0.2.2 → imagex-0.4.0}/imagex.egg-info/entry_points.txt +0 -0
  38. {imagex-0.2.2 → imagex-0.4.0}/imagex.egg-info/requires.txt +0 -0
  39. {imagex-0.2.2 → imagex-0.4.0}/imagex.egg-info/top_level.txt +0 -0
  40. {imagex-0.2.2 → imagex-0.4.0}/setup.cfg +0 -0
  41. {imagex-0.2.2 → imagex-0.4.0}/tests/test_add_noise.py +0 -0
  42. {imagex-0.2.2 → imagex-0.4.0}/tests/test_convert.py +0 -0
  43. {imagex-0.2.2 → imagex-0.4.0}/tests/test_file_ops.py +0 -0
  44. {imagex-0.2.2 → imagex-0.4.0}/tests/test_flip.py +0 -0
  45. {imagex-0.2.2 → imagex-0.4.0}/tests/test_remove_metadata.py +0 -0
  46. {imagex-0.2.2 → imagex-0.4.0}/tests/test_rename_batch.py +0 -0
  47. {imagex-0.2.2 → imagex-0.4.0}/tests/test_resize.py +0 -0
  48. {imagex-0.2.2 → imagex-0.4.0}/tests/test_rotate.py +0 -0
  49. {imagex-0.2.2 → imagex-0.4.0}/tests/test_watermark.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: imagex
3
- Version: 0.2.2
3
+ Version: 0.4.0
4
4
  Summary: All-in-one image processing CLI — resize, convert, watermark, compress, and more
5
5
  Author-email: kushal1o1 <kushal1o1@users.noreply.github.com>
6
6
  License: MIT License
@@ -67,7 +67,9 @@ Dynamic: license-file
67
67
  ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
68
68
  ```
69
69
 
70
- Image processing CLI tool — right in your terminal.
70
+ Image processing CLI tool - right in your terminal.
71
+
72
+ Runs entirely on your computer. No uploads, no accounts. Interactive menu, no flags to remember.
71
73
 
72
74
  ```bash
73
75
  pip install imagex
@@ -84,29 +86,33 @@ Navigate to any folder with images and run `imagex`.
84
86
  | Flip | Mirror horizontally or vertically |
85
87
  | Remove Metadata | Strip EXIF/XMP/IPTC (incl. AI generation markers) |
86
88
  | Convert Format | JPG ↔ PNG ↔ WEBP ↔ TIFF ↔ BMP ↔ GIF ↔ HEIC |
87
- | Compress / Optimize | Reduce file size with quality slider |
89
+ | Compress / Optimize | Shrink to a target size (e.g. `300kb`, `3mb`) or use a quality slider |
88
90
  | Resize | Percentage, exact dimensions, fit within bounds |
89
91
  | Rename Batch | Pattern-based renaming (%n, %o) |
90
92
  | Add Noise | Gaussian or salt & pepper (bypass AI detection) |
91
93
  | Watermark | Add text/image or remove existing |
94
+ | Grayscale / B&W | Convert to grayscale or true black & white |
95
+ | Invert Colors | Negative effect, invert all colors |
96
+ | Convert to PDF | Combine selected images into one PDF (one page per image) |
92
97
 
93
98
  Full details in [OPERATIONS.md](https://github.com/kushal1o1/ImageX/blob/main/OPERATIONS.md).
94
99
 
95
100
  ## Install
96
101
 
97
102
  ```bash
98
- # From PyPI (recommended)
99
- pip install imagex
100
-
101
- # Dev mode from repo (changes take effect immediately)
102
- pip install -e .
103
+ pip install imagex # from PyPI
104
+ pip install imagex[heif] # optional: HEIC support
103
105
  ```
104
106
 
105
- Then run `imagex` from any folder.
107
+ Dev mode from the repo: `pip install -e ".[dev]"`
108
+
109
+ ## Built with
110
+
111
+ Built on [Pillow](https://python-pillow.org) for image work, [rich](https://github.com/Textualize/rich) for terminal output, and [questionary](https://github.com/tmbo/questionary) for the menus. The math is light as well :)
106
112
 
107
- ## Adding Features
113
+ ## Contributing
108
114
 
109
- See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md) for the contribution guide.
115
+ See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md).
110
116
 
111
117
  ## License
112
118
 
@@ -7,7 +7,9 @@
7
7
  ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
8
8
  ```
9
9
 
10
- Image processing CLI tool — right in your terminal.
10
+ Image processing CLI tool - right in your terminal.
11
+
12
+ Runs entirely on your computer. No uploads, no accounts. Interactive menu, no flags to remember.
11
13
 
12
14
  ```bash
13
15
  pip install imagex
@@ -24,29 +26,33 @@ Navigate to any folder with images and run `imagex`.
24
26
  | Flip | Mirror horizontally or vertically |
25
27
  | Remove Metadata | Strip EXIF/XMP/IPTC (incl. AI generation markers) |
26
28
  | Convert Format | JPG ↔ PNG ↔ WEBP ↔ TIFF ↔ BMP ↔ GIF ↔ HEIC |
27
- | Compress / Optimize | Reduce file size with quality slider |
29
+ | Compress / Optimize | Shrink to a target size (e.g. `300kb`, `3mb`) or use a quality slider |
28
30
  | Resize | Percentage, exact dimensions, fit within bounds |
29
31
  | Rename Batch | Pattern-based renaming (%n, %o) |
30
32
  | Add Noise | Gaussian or salt & pepper (bypass AI detection) |
31
33
  | Watermark | Add text/image or remove existing |
34
+ | Grayscale / B&W | Convert to grayscale or true black & white |
35
+ | Invert Colors | Negative effect, invert all colors |
36
+ | Convert to PDF | Combine selected images into one PDF (one page per image) |
32
37
 
33
38
  Full details in [OPERATIONS.md](https://github.com/kushal1o1/ImageX/blob/main/OPERATIONS.md).
34
39
 
35
40
  ## Install
36
41
 
37
42
  ```bash
38
- # From PyPI (recommended)
39
- pip install imagex
40
-
41
- # Dev mode from repo (changes take effect immediately)
42
- pip install -e .
43
+ pip install imagex # from PyPI
44
+ pip install imagex[heif] # optional: HEIC support
43
45
  ```
44
46
 
45
- Then run `imagex` from any folder.
47
+ Dev mode from the repo: `pip install -e ".[dev]"`
48
+
49
+ ## Built with
50
+
51
+ Built on [Pillow](https://python-pillow.org) for image work, [rich](https://github.com/Textualize/rich) for terminal output, and [questionary](https://github.com/tmbo/questionary) for the menus. The math is light as well :)
46
52
 
47
- ## Adding Features
53
+ ## Contributing
48
54
 
49
- See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md) for the contribution guide.
55
+ See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md).
50
56
 
51
57
  ## License
52
58
 
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"
@@ -12,7 +12,8 @@ from rich.panel import Panel
12
12
  from imagex import __version__
13
13
  from imagex.features import get_features
14
14
  from imagex.utils.file_ops import find_images
15
- from imagex.utils.progress import process_files
15
+ from imagex.utils.progress import process_batch, process_files
16
+ from imagex.utils.wizard import BACK, run_steps
16
17
 
17
18
  console = Console()
18
19
 
@@ -103,7 +104,7 @@ def select_features() -> Optional[list[str]]:
103
104
  return selected
104
105
 
105
106
 
106
- def ask_output_mode() -> tuple[str, Optional[Path]]:
107
+ def ask_output_mode() -> tuple[str, Optional[Path]] | str | None:
107
108
  mode = questionary.select(
108
109
  "Where should the processed images go?",
109
110
  choices=[
@@ -119,21 +120,28 @@ def ask_output_mode() -> tuple[str, Optional[Path]]:
119
120
  title="Save to custom folder",
120
121
  value="custom",
121
122
  ),
123
+ questionary.Separator(),
124
+ questionary.Choice(title="← Back", value=BACK),
122
125
  ],
123
126
  ).ask()
124
127
 
128
+ if mode in (BACK, None):
129
+ return mode
130
+
125
131
  output_dir = None
126
132
  if mode == "custom":
127
133
  custom = questionary.text(
128
134
  "Enter output folder path:",
129
135
  validate=lambda p: len(p.strip()) > 0 or "Path cannot be empty",
130
136
  ).ask()
137
+ if custom is None: # Ctrl+C / Esc on the prompt: cancel the flow
138
+ return None
131
139
  output_dir = Path(custom.strip())
132
140
 
133
141
  return mode, output_dir
134
142
 
135
143
 
136
- def select_files(all_files: list[Path]) -> Optional[list[Path]]:
144
+ def select_files(all_files: list[Path]) -> list[Path] | str | None:
137
145
  if not all_files:
138
146
  return None
139
147
 
@@ -153,9 +161,13 @@ def select_files(all_files: list[Path]) -> Optional[list[Path]]:
153
161
 
154
162
  selected = questionary.checkbox(
155
163
  "Which images to process? (Space to toggle, Enter to confirm)",
156
- choices=[all_choice] + file_choices,
164
+ choices=[all_choice, *file_choices, questionary.Separator(),
165
+ questionary.Choice(title="← Back", value=BACK)],
157
166
  ).ask()
158
167
 
168
+ if selected and BACK in selected:
169
+ return BACK
170
+
159
171
  if not selected:
160
172
  return None
161
173
 
@@ -188,49 +200,64 @@ def main():
188
200
  try:
189
201
  show_banner()
190
202
 
191
- selected = select_features()
192
- if selected is None:
193
- console.print("[yellow]No feature selected. Exiting.[/yellow]")
194
- return
203
+ features = get_features()
195
204
 
196
205
  all_files = find_images(Path.cwd())
197
206
  if not all_files:
198
207
  console.print("[red]No image files found in current directory.[/red]")
199
- console.print("[dim]Supported: .jpg .jpeg .png .webp .tiff .tif .bmp .gif .ico[/dim]")
208
+ console.print(
209
+ "[dim]Supported: .jpg .jpeg .png .webp .tiff .tif .bmp .gif .ico[/dim]"
210
+ )
200
211
  return
201
212
 
202
- files = select_files(all_files)
203
- if not files:
204
- console.print("[yellow]No files selected. Exiting.[/yellow]")
205
- return
213
+ def step_features(_results):
214
+ return select_features()
206
215
 
207
- console.print(f"[green]Selected {len(files)} image(s)[/green]")
216
+ def step_files(_results):
217
+ files = select_files(all_files)
218
+ if files not in (None, BACK):
219
+ console.print(f"[green]Selected {len(files)} image(s)[/green]")
220
+ return files
208
221
 
209
- features = get_features()
210
- any_needs_output = any(
211
- info.get("needs_output", True)
212
- for name, info in features.items()
213
- if name in selected
214
- )
222
+ def step_output(results):
223
+ selected = results[0]
224
+ needs_output = any(
225
+ features.get(name, {}).get("needs_output", True)
226
+ for name in selected
227
+ )
228
+ return ask_output_mode() if needs_output else ("overwrite", None)
215
229
 
216
- if any_needs_output:
217
- mode, output_dir = ask_output_mode()
218
- else:
219
- mode, output_dir = "overwrite", None
230
+ result = run_steps([step_features, step_files, step_output])
231
+ if result is None:
232
+ console.print("[yellow]Nothing to do. Exiting.[/yellow]")
233
+ return
234
+
235
+ selected, files, (mode, output_dir) = result
220
236
 
221
237
  for feature_name in selected:
222
238
  info = features[feature_name]
223
239
  ask_args = info.get("ask_args")
224
240
  feature_args = ask_args(files) if ask_args else {}
225
241
  console.print(f"\n[bold]→ {info['name']}[/bold]")
226
- process_files(
227
- files=files,
228
- process_func=info["run"],
229
- feature_name=info["name"],
230
- output_mode=mode,
231
- output_dir=output_dir,
232
- args=feature_args,
233
- )
242
+ if info.get("run_batch"):
243
+ process_batch(
244
+ files=files,
245
+ batch_func=info["run_batch"],
246
+ feature_name=info["name"],
247
+ output_mode=mode,
248
+ output_name=info["output_name"],
249
+ output_dir=output_dir,
250
+ args=feature_args,
251
+ )
252
+ else:
253
+ process_files(
254
+ files=files,
255
+ process_func=info["run"],
256
+ feature_name=info["name"],
257
+ output_mode=mode,
258
+ output_dir=output_dir,
259
+ args=feature_args,
260
+ )
234
261
 
235
262
  console.print("\n[bold green]✓ All done![/bold green]")
236
263
  _check_version()
@@ -11,12 +11,18 @@ def _register(module):
11
11
  run_func = getattr(module, "run", None)
12
12
  ask_args_func = getattr(module, "ask_args", None)
13
13
  needs_output = getattr(module, "NEEDS_OUTPUT_MODE", True)
14
+ # Batch features take every selected file at once and write one output
15
+ # (e.g. a multi-page PDF) instead of one output per file.
16
+ batch_func = getattr(module, "run_batch", None)
17
+ output_name = getattr(module, "OUTPUT_NAME", None)
14
18
 
15
19
  if name and run_func:
16
20
  REGISTRY[name] = {
17
21
  "name": name,
18
22
  "description": description,
19
23
  "run": run_func,
24
+ "run_batch": batch_func,
25
+ "output_name": output_name,
20
26
  "ask_args": ask_args_func,
21
27
  "needs_output": needs_output,
22
28
  "module": module.__name__,
@@ -0,0 +1,237 @@
1
+ import io
2
+ import re
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import Any, Optional
6
+
7
+ import questionary
8
+ from PIL import Image
9
+ from rich.console import Console
10
+
11
+ NAME = "Compress / Optimize"
12
+ DESCRIPTION = "Reduce file size (quality slider or target size in KB)"
13
+
14
+ console = Console()
15
+
16
+ MODE_QUALITY = "Quality slider (1-100)"
17
+ MODE_TARGET = "Target size (e.g. under 300 KB)"
18
+
19
+
20
+ def ask_args(files: list[Path]) -> dict[str, Any]:
21
+ mode = questionary.select(
22
+ "How do you want to compress?",
23
+ choices=[MODE_TARGET, MODE_QUALITY],
24
+ ).ask()
25
+
26
+ if mode == MODE_TARGET:
27
+ size = questionary.text(
28
+ "Max size per image (e.g. 300kb, 3mb, 1.5 MB; no unit = KB):",
29
+ default="300kb",
30
+ validate=lambda v: parse_size(v) is not None or "Try 300kb, 3mb or 1.5mb",
31
+ ).ask()
32
+ return {"target_bytes": parse_size(size)}
33
+
34
+ quality = questionary.text(
35
+ "Quality (1-100):",
36
+ default="80",
37
+ validate=lambda v: v.isdigit() and 1 <= int(v) <= 100 or "Enter a number 1-100",
38
+ ).ask()
39
+
40
+ return {"quality": max(1, min(100, int(quality)))}
41
+
42
+
43
+ def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
44
+ if args is None:
45
+ msg = "args required for compress (quality or target_bytes)"
46
+ raise ValueError(msg)
47
+
48
+ img = Image.open(file)
49
+ meta = {}
50
+ if exif := img.info.get("exif"):
51
+ meta["exif"] = exif
52
+ if icc := img.info.get("icc_profile"):
53
+ meta["icc_profile"] = icc
54
+ fmt = img.format
55
+ original_size = file.stat().st_size
56
+
57
+ target = args.get("target_bytes")
58
+ note = ""
59
+ if target and original_size <= target:
60
+ # Already under the target: don't re-encode (that would only lose quality).
61
+ if output_path.resolve() != file.resolve():
62
+ shutil.copyfile(file, output_path)
63
+ note = "already under target, left unchanged"
64
+ elif target:
65
+ note = _fit_to_target(img, output_path, fmt, meta, target)
66
+ else:
67
+ _encode(img, output_path, fmt, args.get("quality", 80), meta)
68
+
69
+ new_size = output_path.stat().st_size
70
+ saved = original_size - new_size
71
+ pct = (1 - new_size / original_size) * 100 if original_size else 0
72
+ console.print(
73
+ f" [dim]{file.name}: {_fmt_size(original_size)} → {_fmt_size(new_size)} "
74
+ f"({'−' if saved >= 0 else '+'}{abs(pct):.0f}%)[/dim]"
75
+ + (f" [yellow]{note}[/yellow]" if note else "")
76
+ )
77
+
78
+ return True
79
+
80
+
81
+ def _encode(img: Image.Image, dest, fmt: Optional[str], quality: int, meta: dict):
82
+ if fmt == "JPEG":
83
+ _compress_jpeg(img, dest, quality, meta)
84
+ elif fmt == "PNG":
85
+ _compress_png(img, dest, quality, meta)
86
+ elif fmt == "WEBP":
87
+ _compress_webp(img, dest, quality, meta)
88
+ else:
89
+ _compress_other(img, dest, fmt, quality, meta)
90
+
91
+
92
+ def _fit_to_target(
93
+ img: Image.Image, output_path: Path, fmt: Optional[str], meta: dict, target: int,
94
+ ) -> str:
95
+ """Write the image as small as possible while staying <= target bytes.
96
+
97
+ Lossy formats (JPEG, WEBP) get a binary search over quality, and PNG
98
+ falls back to palette reduction if lossless is too big. Returns a note
99
+ for the console if the target could not be met.
100
+ """
101
+ if fmt in ("JPEG", "WEBP"):
102
+ def encode(q: int) -> bytes:
103
+ buf = io.BytesIO()
104
+ _encode(img, buf, fmt, q, meta)
105
+ return buf.getvalue()
106
+
107
+ data, best = _search_largest(encode, lo=1, hi=95, target=target)
108
+ output_path.write_bytes(data)
109
+ if len(data) > target:
110
+ return f"can't reach target, smallest possible (quality {best})"
111
+ return f"quality {best}"
112
+
113
+ if fmt == "PNG":
114
+ data = _encode_bytes(img, fmt, 100, meta)
115
+ if len(data) <= target:
116
+ output_path.write_bytes(data)
117
+ return ""
118
+
119
+ def encode_colors(c: int) -> bytes:
120
+ return _png_palette_bytes(img, c, meta)
121
+
122
+ data, colors = _search_largest(encode_colors, lo=2, hi=256, target=target)
123
+ output_path.write_bytes(data)
124
+ if len(data) > target:
125
+ return f"can't reach target, smallest possible ({colors} colors)"
126
+ return f"{colors} colors"
127
+
128
+ # BMP, GIF, TIFF, ...: no quality knob to turn.
129
+ _encode(img, output_path, fmt, 80, meta)
130
+ if output_path.stat().st_size > target:
131
+ return f"{fmt} has no quality setting, can't reach target"
132
+ return ""
133
+
134
+
135
+ def _search_largest(encode, lo: int, hi: int, target: int):
136
+ """Return (bytes, param) for the largest param in [lo, hi] whose output fits.
137
+
138
+ Assumes output size grows with the parameter. If even ``lo`` is too big,
139
+ returns the ``lo`` encoding so the caller can still write the smallest
140
+ result.
141
+ """
142
+ smallest = encode(lo)
143
+ if len(smallest) > target:
144
+ return smallest, lo
145
+
146
+ best_data, best = smallest, lo
147
+ while lo <= hi:
148
+ mid = (lo + hi) // 2
149
+ data = encode(mid)
150
+ if len(data) <= target:
151
+ best_data, best = data, mid
152
+ lo = mid + 1
153
+ else:
154
+ hi = mid - 1
155
+ return best_data, best
156
+
157
+
158
+ def _encode_bytes(img: Image.Image, fmt: str, quality: int, meta: dict) -> bytes:
159
+ buf = io.BytesIO()
160
+ _encode(img, buf, fmt, quality, meta)
161
+ return buf.getvalue()
162
+
163
+
164
+ def _png_palette_bytes(img: Image.Image, colors: int, meta: dict) -> bytes:
165
+ flat = _flatten(img)
166
+ buf = io.BytesIO()
167
+ flat.quantize(colors=colors, method=Image.Quantize.MEDIANCUT).save(
168
+ buf, format="PNG", optimize=True, **meta,
169
+ )
170
+ return buf.getvalue()
171
+
172
+
173
+ def _flatten(img: Image.Image) -> Image.Image:
174
+ if img.mode == "RGBA":
175
+ bg = Image.new("RGB", img.size, (255, 255, 255))
176
+ bg.paste(img, mask=img.split()[3])
177
+ return bg
178
+ if img.mode != "RGB":
179
+ return img.convert("RGB")
180
+ return img
181
+
182
+
183
+ def _compress_jpeg(img: Image.Image, dest, quality: int, meta: dict):
184
+ img = _flatten(img)
185
+ img.save(dest, format="JPEG", quality=quality, optimize=True, **meta)
186
+
187
+
188
+ def _compress_png(img: Image.Image, dest, quality: int, meta: dict):
189
+ if quality < 50:
190
+ colors = max(quality * 2, 16)
191
+ img = _flatten(img).quantize(colors=colors, method=Image.Quantize.MEDIANCUT)
192
+ img.save(dest, format="PNG", optimize=True, **meta)
193
+ else:
194
+ img.save(dest, format="PNG", optimize=True, **meta)
195
+
196
+
197
+ def _compress_webp(img: Image.Image, dest, quality: int, meta: dict):
198
+ img.save(dest, format="WEBP", quality=quality, **meta)
199
+
200
+
201
+ def _compress_other(img: Image.Image, dest, fmt: Optional[str], quality: int, meta: dict):
202
+ params = {"format": fmt, **meta}
203
+ if fmt == "GIF":
204
+ params["save_all"] = True
205
+ img.save(dest, **params)
206
+
207
+
208
+ _SIZE_UNITS = {
209
+ "b": 1,
210
+ "kb": 1024,
211
+ "k": 1024,
212
+ "mb": 1024**2,
213
+ "m": 1024**2,
214
+ "gb": 1024**3,
215
+ }
216
+ _SIZE_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([a-zA-Z]*)\s*$")
217
+
218
+
219
+ def parse_size(text: str) -> Optional[int]:
220
+ """Turn '300kb', '3 MB', '1.5mb' or '300' (KB) into bytes. None if invalid."""
221
+ match = _SIZE_RE.match(text or "")
222
+ if not match:
223
+ return None
224
+ number, unit = match.groups()
225
+ multiplier = _SIZE_UNITS.get(unit.lower() or "kb")
226
+ if multiplier is None or float(number) <= 0:
227
+ return None
228
+ return int(float(number) * multiplier)
229
+
230
+
231
+ def _fmt_size(size: int) -> str:
232
+ value = float(size)
233
+ for unit in ("B", "KB", "MB"):
234
+ if value < 1024:
235
+ return f"{value:.0f} {unit}"
236
+ value /= 1024
237
+ return f"{value:.1f} GB"
@@ -0,0 +1,57 @@
1
+ from pathlib import Path
2
+ from typing import Any, Optional
3
+
4
+ import questionary
5
+ from PIL import Image
6
+
7
+ NAME = "Grayscale / B&W"
8
+ DESCRIPTION = "Convert images to grayscale or true black & white"
9
+
10
+ MODES = {
11
+ "Grayscale (luminosity)": "grayscale",
12
+ "True Black & White (threshold)": "bw",
13
+ }
14
+
15
+
16
+ def ask_args(files: list[Path]) -> dict[str, Any]:
17
+ mode_label = questionary.select(
18
+ "Mode:",
19
+ choices=list(MODES.keys()),
20
+ ).ask()
21
+
22
+ args = {"mode": MODES[mode_label]}
23
+
24
+ if MODES[mode_label] == "bw":
25
+ threshold = questionary.text(
26
+ "Threshold (0-255, lower = more black):",
27
+ default="128",
28
+ validate=lambda v: v.isdigit() and 0 <= int(v) <= 255 or "Enter 0-255",
29
+ ).ask()
30
+ args["threshold"] = int(threshold)
31
+
32
+ return args
33
+
34
+
35
+ def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
36
+ if args is None:
37
+ msg = "args required for grayscale"
38
+ raise ValueError(msg)
39
+
40
+ img = Image.open(file)
41
+ kw = {"format": img.format or "JPEG"}
42
+ if exif := img.info.get("exif"):
43
+ kw["exif"] = exif
44
+ if icc := img.info.get("icc_profile"):
45
+ kw["icc_profile"] = icc
46
+
47
+ gray = img.convert("L")
48
+
49
+ if args["mode"] == "grayscale":
50
+ gray.save(str(output_path), **kw)
51
+ else:
52
+ threshold = args.get("threshold", 128)
53
+ bw = gray.point(lambda p: 255 if p > threshold else 0, mode="1")
54
+ bw = bw.convert("L")
55
+ bw.save(str(output_path), **kw)
56
+
57
+ return True
@@ -0,0 +1,30 @@
1
+ from pathlib import Path
2
+ from typing import Any, Optional
3
+
4
+ from PIL import Image, ImageOps
5
+
6
+ NAME = "Invert Colors"
7
+ DESCRIPTION = "Invert image colors (negative effect)"
8
+
9
+
10
+ def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
11
+ img = Image.open(file)
12
+ kw = {"format": img.format or "JPEG"}
13
+ if exif := img.info.get("exif"):
14
+ kw["exif"] = exif
15
+ if icc := img.info.get("icc_profile"):
16
+ kw["icc_profile"] = icc
17
+
18
+ if img.mode == "RGBA":
19
+ r, g, b, a = img.split()
20
+ rgb = Image.merge("RGB", (r, g, b))
21
+ inverted = ImageOps.invert(rgb)
22
+ r2, g2, b2 = inverted.split()
23
+ img = Image.merge("RGBA", (r2, g2, b2, a))
24
+ else:
25
+ if img.mode != "RGB":
26
+ img = img.convert("RGB")
27
+ img = ImageOps.invert(img)
28
+
29
+ img.save(str(output_path), **kw)
30
+ return True
@@ -0,0 +1,47 @@
1
+ from pathlib import Path
2
+ from typing import Any, Optional
3
+
4
+ from PIL import Image, ImageOps
5
+
6
+ NAME = "Convert to PDF"
7
+ DESCRIPTION = "Combine selected images into one PDF (one page per image)"
8
+
9
+ # Batch feature: receives every selected file at once and writes one PDF.
10
+ OUTPUT_NAME = "imagex_output.pdf"
11
+
12
+
13
+ def run_batch(
14
+ files: list[Path], output_path: Path, args: Optional[dict[str, Any]] = None,
15
+ ) -> bool:
16
+ if not files:
17
+ msg = "no images to convert"
18
+ raise ValueError(msg)
19
+
20
+ pages = [_load_page(Path(f)) for f in files]
21
+ first, rest = pages[0], pages[1:]
22
+ first.save(
23
+ str(output_path),
24
+ format="PDF",
25
+ save_all=True,
26
+ append_images=rest,
27
+ resolution=72.0, # 1 pixel = 1 point, so each page is the full image
28
+ )
29
+ return True
30
+
31
+
32
+ def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
33
+ return run_batch([file], output_path, args)
34
+
35
+
36
+ def _load_page(path: Path) -> Image.Image:
37
+ """Open an image as a PDF-ready page (RGB or grayscale, no alpha)."""
38
+ with Image.open(path) as img:
39
+ img = ImageOps.exif_transpose(img)
40
+ if img.mode in ("RGB", "L", "CMYK"):
41
+ return img.copy()
42
+ if img.mode in ("RGBA", "LA", "PA", "P"):
43
+ rgba = img.convert("RGBA")
44
+ page = Image.new("RGB", rgba.size, (255, 255, 255))
45
+ page.paste(rgba, mask=rgba.split()[3])
46
+ return page
47
+ return img.convert("RGB")