Skip to content

Use aspect ratio when making thumbnails#857

Merged
tankerkiller125 merged 5 commits intomainfrom
mk/use-aspect-for-thumbnails
Jul 4, 2025
Merged

Use aspect ratio when making thumbnails#857
tankerkiller125 merged 5 commits intomainfrom
mk/use-aspect-for-thumbnails

Conversation

@tankerkiller125
Copy link
Copy Markdown
Contributor

@tankerkiller125 tankerkiller125 commented Jul 4, 2025

What type of PR is this?

  • bug

What this PR does / why we need it:

Resolves issue where thumbnails were not taking aspect ratios into account. This PR takes the aspect ratio into account and still keeps the max size correct.

Which issue(s) this PR fixes:

Fixes: #848
Fixes: #844

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Thumbnails are now generated with dynamic dimensions that preserve the original image's aspect ratio, ensuring they fit within the configured maximum size.
    • Improved image orientation handling for thumbnails, supporting multiple image formats with correct EXIF orientation applied.
    • Added image transformation utilities to apply flips and rotations based on EXIF metadata.
  • Bug Fixes

    • Prevented distortion of thumbnails by maintaining the correct aspect ratio for all supported image formats.
    • Extended content type detection to recognize additional image formats like JPEG XL.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jul 4, 2025

Warning

Rate limit exceeded

@tankerkiller125 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 7 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8bef7b2 and 6e5cca8.

⛔ Files ignored due to path filters (1)
  • backend/go.sum is excluded by !**/*.sum
📒 Files selected for processing (5)
  • backend/app/api/main.go (1 hunks)
  • backend/go.mod (4 hunks)
  • backend/internal/data/repo/repo_item_attachments.go (8 hunks)
  • backend/internal/data/repo/repo_item_attachments_test.go (6 hunks)
  • backend/pkgs/utils/image.go (1 hunks)

Walkthrough

The thumbnail generation logic was refactored to preserve the original image's aspect ratio by calculating scaled dimensions that fit within configured maximum thumbnail sizes. A new helper method centralizes image processing steps including orientation correction, resizing, encoding to WebP, and storage upload. Test calls were updated to include group ID parameters.

Changes

File(s) Change Summary
backend/internal/data/repo/repo_item_attachments.go Refactored thumbnail creation to preserve aspect ratio; added helper method for processing thumbnails; added dimension calculation function; extended content type detection.
backend/internal/data/repo/repo_item_attachments_test.go Updated repository method calls to include group ID parameter in attachment operations.
backend/pkgs/utils/image.go Added image transformation utilities (flip, rotate, apply EXIF orientation) using Go standard library only.
backend/go.mod Added direct dependency on imagemeta package and updated indirect dependencies.
backend/app/api/main.go Modified storage directory path validation to normalize path separators for go-cloud compatibility.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AttachmentRepo
    participant ImageDecoder
    participant Storage

    User->>AttachmentRepo: CreateThumbnail(image)
    AttachmentRepo->>ImageDecoder: Decode image metadata and orientation
    ImageDecoder-->>AttachmentRepo: Return image and orientation
    AttachmentRepo->>AttachmentRepo: ApplyOrientation(image, orientation)
    AttachmentRepo->>AttachmentRepo: calculateThumbnailDimensions(origWidth, origHeight, maxWidth, maxHeight)
    AttachmentRepo->>AttachmentRepo: Resize image to calculated dimensions
    AttachmentRepo->>AttachmentRepo: Encode image as WebP
    AttachmentRepo->>Storage: Upload thumbnail
    Storage-->>AttachmentRepo: Return thumbnail path
    AttachmentRepo->>User: Return thumbnail path
Loading

Assessment against linked issues

Objective Addressed Explanation
Preserve original aspect ratio in generated thumbnails (#848)
Prevent distortion of thumbnails for non-square images (#848)
Correct photo orientation based on EXIF metadata (#844)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Updated test calls to repository methods with group ID parameter (backend/internal/data/repo/repo_item_attachments_test.go) Related to repository method signatures and test setup, unrelated to thumbnail aspect ratio or orientation issues.
Added image transformation utilities in utils/image.go Utility functions support orientation handling but are not explicitly requested by the linked issues.
Added imagemeta dependency and indirect dependency updates (backend/go.mod) Dependency management changes support new image metadata handling, not explicitly part of the linked issues.
Modified storage path validation in main.go Change relates to path normalization for storage backend compatibility, unrelated to thumbnail generation or orientation fixes.

Possibly related PRs

  • More image type support for thumbnails #814: Originally added support for HEIC and JPEG XL image formats and their thumbnail generation, closely related to the current refactoring and extension of thumbnail processing.
  • Abstract Attachment Storage #777: Focused on abstracting attachment storage backends, related to storage upload aspects of thumbnails but not image processing itself.

Suggested labels

⬆️ enhancement

Poem

A thumbnail once squashed in a box,
Now stretches its limbs, free of paradox.
Aspect ratio saved, no more faces so wide—
Images now fit, with their pride dignified.
🎨✨

Let thumbnails rejoice,
Their true shapes—now their choice!


Security Recommendation:
Always validate and sanitize image inputs to prevent malicious payloads or resource exhaustion during thumbnail generation. Consider setting strict limits on image size and format to mitigate potential denial-of-service attacks.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in a Comment
  • Commit Unit Tests in branch mk/use-aspect-for-thumbnails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai bot added the 🕷️ bug Something isn't working label Jul 4, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/internal/data/repo/repo_item_attachments.go (1)

847-874: Add input validation for security hardening.

The aspect ratio calculation logic is mathematically sound and handles edge cases well. However, consider adding input validation to prevent potential misuse.

 func calculateThumbnailDimensions(origWidth, origHeight, maxWidth, maxHeight int) (int, int) {
+	// Validate input parameters
+	if origWidth <= 0 || origHeight <= 0 || maxWidth <= 0 || maxHeight <= 0 {
+		return 1, 1
+	}
+	
 	if origWidth <= maxWidth && origHeight <= maxHeight {
 		return origWidth, origHeight
 	}

Security recommendation: While the current implementation is secure, adding explicit input validation provides defense-in-depth against potential integer overflow or division-by-zero scenarios, even though the current callers pass valid values.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8bef7b2 and af9db50.

📒 Files selected for processing (1)
  • backend/internal/data/repo/repo_item_attachments.go (6 hunks)
🧰 Additional context used
🧠 Learnings (1)
backend/internal/data/repo/repo_item_attachments.go (1)
Learnt from: tankerkiller125
PR: sysadminsmedia/homebox#777
File: backend/internal/data/repo/repo_item_attachments.go:187-196
Timestamp: 2025-06-08T00:32:27.457Z
Learning: In the Homebox application, file upload size limits are handled at the admin configuration level elsewhere in the application, not at the individual file processing method level in backend/internal/data/repo/repo_item_attachments.go.
⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 4/4
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 3/4
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 2/4
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 17
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 1/4
  • GitHub Check: Backend Server Tests / Go
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 16
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 15
  • GitHub Check: Frontend Tests / Integration Tests
  • GitHub Check: Frontend Tests / Lint
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (actions)
🔇 Additional comments (2)
backend/internal/data/repo/repo_item_attachments.go (2)

525-527: LGTM! Consistent implementation across all image formats.

The aspect ratio preservation logic is correctly and consistently applied across all supported image formats (JPEG/PNG/GIF, WebP, AVIF, HEIC/HEIF, JPEG XL). The pattern of getting bounds, calculating dimensions, and creating appropriately sized destination images is well-implemented.

Also applies to: 565-567, 605-607, 645-647, 685-687


486-488: Security recommendation: File size limit provides good DoS protection.

The 100MB file size limit effectively prevents resource exhaustion attacks through oversized image uploads. This is a solid security practice for thumbnail generation.

@coderabbitai coderabbitai bot added the go Pull requests that update Go code label Jul 4, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa88637 and 6c79959.

⛔ Files ignored due to path filters (1)
  • backend/go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • backend/go.mod (4 hunks)
  • backend/internal/data/repo/repo_item_attachments.go (8 hunks)
  • backend/pkgs/utils/image.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/go.mod
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/internal/data/repo/repo_item_attachments.go
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Backend Server Tests / Go
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 2/4
  • GitHub Check: Frontend Tests / Lint
  • GitHub Check: Frontend Tests / Integration Tests
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 17
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 15
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 16
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (actions)

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c79959 and 0039c88.

📒 Files selected for processing (3)
  • backend/app/api/main.go (1 hunks)
  • backend/internal/data/repo/repo_item_attachments.go (8 hunks)
  • backend/pkgs/utils/image.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/internal/data/repo/repo_item_attachments.go
  • backend/pkgs/utils/image.go
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 15
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 17
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 4/4
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 16
  • GitHub Check: Frontend Tests / Lint
  • GitHub Check: Backend Server Tests / Go
  • GitHub Check: Frontend Tests / Integration Tests
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (actions)

@tankerkiller125
Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jul 4, 2025

✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai bot added the ⬆️ enhancement New feature or request label Jul 4, 2025
@tankerkiller125 tankerkiller125 merged commit be1f3c0 into main Jul 4, 2025
24 of 25 checks passed
@tankerkiller125 tankerkiller125 deleted the mk/use-aspect-for-thumbnails branch July 4, 2025 15:44
@StanislavJochman
Copy link
Copy Markdown
Contributor

I believe this PR introduced bug where images are squared all the time.
Screenshot 2025-07-30 at 04 26 24

@tankerkiller125
Copy link
Copy Markdown
Contributor Author

I tested this PR on all the supported formats, and all of them where coming out in the correct aspect ratio, which version @StanislavJochman are you running? This PR has not made it into a tagged release yet.

@StanislavJochman
Copy link
Copy Markdown
Contributor

I tested this PR on all the supported formats, and all of them where coming out in the correct aspect ratio, which version @StanislavJochman are you running? This PR has not made it into a tagged release yet.

I am running Version: v0.20.2 Build:

@tankerkiller125
Copy link
Copy Markdown
Contributor Author

@StanislavJochman The aspect ratio being broken is a known issue in v0.20.2, this PR will fix it once a tagged release is made.

@samuelkdavis
Copy link
Copy Markdown

@tankerkiller125 is this still an issue?

Image:
image
Card:
image

Version: v0.21.0 Build: 27e9eb2 ~ API

@tonyaellie
Copy link
Copy Markdown
Collaborator

@samuelkdavis see #715

auzroz pushed a commit to auzroz/homebox that referenced this pull request Dec 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🕷️ bug Something isn't working ⬆️ enhancement New feature or request go Pull requests that update Go code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Thumbnail aspect ratio is lost when generating preview Photos are wrong orientation when taken on mobile

4 participants