#1016: ImageService.kt
projectforge-business/src/main/kotlin/org/projectforge/business/image/ImageService.kt Service (Image Processing), projectforge-business/src/main/kotlin/org/projectforge/business/image/ImageService.kt 388 lines · 247 code · 94 comments · 47 blank
Spring @Service providing intelligent image resizing and compression for ProjectForge addressbook images. Uses a multi-strategy approach: JPEG quality reduction, binary search on dimensions, JPEG-first-then-PNG fallback.
Architecture
Shrinking Algorithm (shrinkToMaxFileSize)
The service implements a two-phase approach to shrink images to a target file size:
- Format Conversion: Attempts JPEG conversion first (optimal compression). Falls back to PNG if the image has transparency (alpha channel) that JPEG cannot handle. Image type detection uses magic bytes.
- Strategy 1 — JPEG Quality Reduction: Tests quality levels 0.85, 0.8, 0.7 sequentially. Returns immediately if a quality level achieves the optimal range (95-100% of max size).
- Strategy 2 — Binary Search Scaling: If quality reduction alone is insufficient, performs binary search on a scale factor (0.0-1.0) applied to image dimensions. Minimum dimension guard at 100px prevents unusable images. Uses the best JPEG quality from Strategy 1.
Key Design Decisions
- Optimal Range Targeting: Aiming for 95-100% of max size rather than just "under the limit" maximizes image quality within constraints.
- JPEG-First Strategy: JPEG typically compresses photos 5-10x better than PNG, so conversion is attempted first.
- Magic Byte Detection:
detectImageType() checks raw bytes for JPEG (FF D8 FF), GIF (GIF), and PNG (89 50 4E 47) signatures, avoiding dependency on file extensions.
- Resize with Aspect Ratio:
resizeImagePreserveRatio() calculates a min-scale from both width and height to fit within bounds while preserving aspect ratio.
ImageResult Data Class
Contains bytes: ByteArray and imageType: ImageType. Overrides equals/hashCode with content-aware comparison using contentEquals/contentHashCode.
Git History
868d6abb7 2025 -> 2026
eeaafe0df Adresses: image-handling: minimizing images approx. 100k with JPEG, recalculation of images and previews for admins.