-
-
Notifications
You must be signed in to change notification settings - Fork 1
refactor: Remove jpegtran dependency and update ImageRotator for metadata-first rotation approach #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
duartebarbosadev
merged 3 commits into
main
from
fix-release-build-context-menu-on-images-and-rotation-doesn't-show-up
Sep 10, 2025
Merged
refactor: Remove jpegtran dependency and update ImageRotator for metadata-first rotation approach #44
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
db57ba3
refactor: Remove jpegtran dependency and update ImageRotator for meta…
duartebarbosadev 50b93ff
refactor: Update docstring for ImageRotator and enhance test initiali…
duartebarbosadev d944e43
refactor: Clean up docstring for ImageRotator and remove redundant co…
duartebarbosadev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,16 +1,12 @@ | ||||||
| import os | ||||||
| import logging | ||||||
| import subprocess | ||||||
| import tempfile | ||||||
| from typing import Literal, Tuple | ||||||
| from PIL import Image, ImageOps | ||||||
|
|
||||||
| # Use the new pyexiv2 abstraction layer | ||||||
| from core.pyexiv2_wrapper import PyExiv2Operations, safe_pyexiv2_image | ||||||
|
|
||||||
| from pathlib import Path | ||||||
| from core.image_file_ops import ImageFileOperations | ||||||
| from core.app_settings import JPEGTRAN_TIMEOUT_SECONDS | ||||||
| import piexif # For EXIF manipulation with Pillow | ||||||
| from pillow_heif import HeifImageFile # For HEIF/HEIC support | ||||||
|
|
||||||
|
|
@@ -19,6 +15,14 @@ | |||||
| # Rotation directions | ||||||
| RotationDirection = Literal["clockwise", "counterclockwise", "180"] | ||||||
|
|
||||||
| """ | ||||||
| Handles image rotation with support for: | ||||||
| 1. Standard rotation for JPEG, PNG and other formats | ||||||
| 2. Metadata-only rotation for RAW formats (ARW, CR2, NEF, etc.) | ||||||
| 3. Metadata-only rotation for HEIF/HEIC formats | ||||||
| 4. XMP orientation metadata updates for all supported formats | ||||||
| """ | ||||||
|
|
||||||
|
|
||||||
| class ImageRotator: | ||||||
| # Define supported image formats for different rotation types | ||||||
|
|
@@ -52,33 +56,6 @@ class ImageRotator: | |||||
| ".heif", | ||||||
| ".heic", | ||||||
| } | ||||||
| """ | ||||||
| Handles image rotation with support for: | ||||||
| 1. Lossless rotation for JPEG files (using jpegtran if available) | ||||||
| 2. Standard rotation for PNG and other formats | ||||||
| 3. XMP orientation metadata updates for all supported formats | ||||||
| """ | ||||||
|
|
||||||
| def __init__(self): | ||||||
| self.jpegtran_available = self._check_jpegtran_availability() | ||||||
| logger.info(f"jpegtran availability: {self.jpegtran_available}") | ||||||
|
|
||||||
| def _check_jpegtran_availability(self) -> bool: | ||||||
| """Check if jpegtran is available in the system PATH.""" | ||||||
| try: | ||||||
| result = subprocess.run( | ||||||
| ["jpegtran", "-version"], | ||||||
| capture_output=True, | ||||||
| text=True, | ||||||
| timeout=JPEGTRAN_TIMEOUT_SECONDS, | ||||||
| ) | ||||||
| return result.returncode == 0 | ||||||
| except ( | ||||||
| subprocess.SubprocessError, | ||||||
| FileNotFoundError, | ||||||
| subprocess.TimeoutExpired, | ||||||
| ): | ||||||
| return False | ||||||
|
|
||||||
| def _get_current_orientation(self, image_path: str) -> int: | ||||||
| """Get current EXIF orientation value (1-8, default 1).""" | ||||||
|
|
@@ -144,77 +121,6 @@ def _calculate_new_orientation( | |||||
|
|
||||||
| return current_orientation | ||||||
|
|
||||||
| def _rotate_jpeg_lossless( | ||||||
| self, image_path: str, direction: RotationDirection | ||||||
| ) -> bool: | ||||||
| """ | ||||||
| Perform lossless JPEG rotation using jpegtran. | ||||||
| Returns True if successful, False otherwise. | ||||||
| """ | ||||||
| if not self.jpegtran_available: | ||||||
| return False | ||||||
|
|
||||||
| try: | ||||||
| # Map rotation direction to jpegtran parameters | ||||||
| if direction == "clockwise": | ||||||
| transform = "-rotate 90" | ||||||
| elif direction == "counterclockwise": | ||||||
| transform = "-rotate 270" | ||||||
| elif direction == "180": | ||||||
| transform = "-rotate 180" | ||||||
| else: | ||||||
| return False | ||||||
|
|
||||||
| # Create temporary file for output | ||||||
| with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as temp_file: | ||||||
| temp_path = temp_file.name | ||||||
|
|
||||||
| # Execute jpegtran | ||||||
| cmd = f'jpegtran -copy all -perfect {transform} "{image_path}"' | ||||||
| result = subprocess.run( | ||||||
| cmd, | ||||||
| shell=True, | ||||||
| capture_output=True, | ||||||
| stdout=open(temp_path, "wb"), | ||||||
| timeout=30, | ||||||
| ) | ||||||
|
|
||||||
| if result.returncode == 0 and os.path.getsize(temp_path) > 0: | ||||||
| # Replace original with rotated version | ||||||
| success, msg = ImageFileOperations.replace_file(temp_path, image_path) | ||||||
| if success: | ||||||
| logger.info( | ||||||
| f"Lossless JPEG rotation successful: {os.path.basename(image_path)}." | ||||||
| ) | ||||||
| else: | ||||||
| logger.error( | ||||||
| f"Lossless JPEG rotation failed during file replacement for '{os.path.basename(image_path)}': {msg}" | ||||||
| ) | ||||||
| return success | ||||||
| else: | ||||||
| logger.warning( | ||||||
| "jpegtran command failed for '%s'. Stderr: %s", | ||||||
| os.path.basename(image_path), | ||||||
| result.stderr.decode(), | ||||||
| ) | ||||||
| return False | ||||||
|
|
||||||
| except Exception as e: | ||||||
| logger.error( | ||||||
| "Error during lossless JPEG rotation for '%s': %s", | ||||||
| os.path.basename(image_path), | ||||||
| e, | ||||||
| exc_info=True, | ||||||
| ) | ||||||
| return False | ||||||
| finally: | ||||||
| # Clean up temp file if it exists | ||||||
| if "temp_path" in locals() and os.path.exists(temp_path): | ||||||
| try: | ||||||
| os.unlink(temp_path) | ||||||
| except OSError: | ||||||
| pass | ||||||
|
|
||||||
| def _rotate_image_standard( | ||||||
| self, image_path: str, direction: RotationDirection | ||||||
| ) -> bool: | ||||||
|
|
@@ -429,15 +335,21 @@ def rotate_image( | |||||
| method_used = "metadata-only" | ||||||
| else: | ||||||
| # Rotate the actual image pixels | ||||||
| if file_ext in self._LOSSLESS_JPEG_FORMATS and self.jpegtran_available: | ||||||
| # Try lossless JPEG rotation first | ||||||
| success = self._rotate_jpeg_lossless(image_path, direction) | ||||||
| method_used = "lossless JPEG" | ||||||
|
|
||||||
| if not success: | ||||||
| # Fallback to standard rotation (lossy for JPEG) | ||||||
| if file_ext in self._LOSSLESS_JPEG_FORMATS: | ||||||
| # For JPEG, try metadata rotation first (lossless), then pixel rotation as fallback | ||||||
| metadata_success, pixel_available, msg = ( | ||||||
| self.try_metadata_rotation_first(image_path, direction) | ||||||
| ) | ||||||
| if metadata_success: | ||||||
| success = True | ||||||
| method_used = "metadata-only (lossless)" | ||||||
| elif pixel_available: | ||||||
| # Fallback to pixel rotation | ||||||
| success = self._rotate_image_standard(image_path, direction) | ||||||
| method_used = "standard (lossy fallback)" | ||||||
| method_used = "standard JPEG (quality=95, lossy fallback)" | ||||||
|
||||||
| method_used = "standard JPEG (quality=95, lossy fallback)" | |
| method_used = "standard JPEG (lossy fallback)" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This module-level docstring is positioned after imports and before the class definition. It should be moved to the top of the file, right after the imports, to follow Python docstring conventions for module documentation.