Skip to content

Conversation

@rahulrajesh21
Copy link
Contributor

/claim #2742

Product Description

Improves image downscaling quality in CommCare by implementing a progressive step-wise scaling approach. This reduces visual artifacts like amplifying light patterns when resizing large images.

Technical Summary

Ticket: #2742
• The original implementation of direct downscaling introduced visual artifacts in images with fine patterns. This change introduces progressive halving to preserve image quality.
• DownScaling is done in multiple halving steps followed by a final scale, instead of a single step.

Image used for testing

Before Implementation (stippled appearance):

1745386706126

After Implementation (improved appearance):

1745574763006

Feature Flag

Safety Assurance

Safety story

Automated test coverage

QA Plan

Labels and Review

  • Do we need to enhance the manual QA test coverage ? If yes, the "QA Note" label is set correctly
  • Does the PR introduce any major changes worth communicating ? If yes, the "Release Note" label is set and a "Release Note" is specified in PR description.
  • Risk label is set correctly
  • The set of people pinged as reviewers is appropriate for the level of risk of the change

@damagatchi
Copy link

Can one of the admins verify this patch?

@coderabbitai
Copy link

coderabbitai bot commented May 4, 2025

📝 Walkthrough

Walkthrough

This change introduces a new private static method, stepDownscale, to the FileUtil class. The method is designed to progressively reduce the size of a bitmap by halving its dimensions multiple times until it is close to the target size, followed by a final scaling step to reach the exact target dimensions. The existing method getBitmapScaledByMaxDimen is updated to utilize this new approach instead of performing a single-step resize. The target width and height are calculated based on the original aspect ratio and the specified maximum dimension, and these values are passed to stepDownscale. Additionally, minor formatting improvements are made to Javadoc comments and code indentation. No changes are made to the public API, error handling, or overall control flow outside of the bitmap scaling logic.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant FileUtil
    participant Bitmap

    Caller->>FileUtil: getBitmapScaledByMaxDimen(originalBitmap, maxDimen)
    FileUtil->>FileUtil: Calculate targetWidth, targetHeight
    FileUtil->>FileUtil: stepDownscale(originalBitmap, targetWidth, targetHeight)
    loop While dimensions > target
        FileUtil->>Bitmap: Scale bitmap to half size
    end
    FileUtil->>Bitmap: Final scale to targetWidth, targetHeight
    FileUtil-->>Caller: Return downscaled bitmap
Loading

Possibly related issues

  • Improve image capture resizing #2742: The changes implement progressive downscaling in FileUtil to reduce aliasing artifacts, directly addressing the image resizing quality issues described in this issue.

Suggested labels

skip-integration-tests

Suggested reviewers

  • shubham1g5

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bf954b0 and bf55933.

📒 Files selected for processing (1)
  • app/src/org/commcare/utils/FileUtil.java (6 hunks)
🔇 Additional comments (6)
app/src/org/commcare/utils/FileUtil.java (6)

158-159: Documentation improvement with correct HTML formatting.

The addition of <p> tags in Javadoc comments improves the generated documentation by creating proper paragraph breaks.


323-324: Documentation improvement with correct HTML formatting.

The addition of <p> tags in Javadoc comments improves the generated documentation by creating proper paragraph breaks.


625-625: Fixed indentation for consistency.

The correct indentation of the return statement improves code readability and maintains consistent style.


703-746: Excellent implementation of progressive downscaling to reduce artifacts.

The new stepDownscale method implements a best practice approach for image downscaling by using multiple steps:

  1. Progressive halving until close to target size
  2. Final scaling to exact dimensions

This technique effectively reduces moiré patterns and aliasing artifacts that occur when downscaling images with fine patterns in a single step. The implementation also handles bitmap recycling properly to prevent memory leaks.


772-782: Good refactoring to leverage the new progressive downscaling.

The modification properly calculates target dimensions and delegates to the new stepDownscale method, maintaining aspect ratio while reducing visual artifacts.


787-787: Added blank line for better code organization.

The additional blank line improves readability by better separating distinct method groups.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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 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.

@shubham1g5
Copy link
Contributor

@rahulrajesh21 Thanks for submitting this, can you fill this up for us to take next steps here.

@rahulrajesh21
Copy link
Contributor Author

@shubham1g5 I have filled out the form.

@shubham1g5
Copy link
Contributor

@damagatchi ok to test

Copy link
Contributor

@shubham1g5 shubham1g5 left a comment

Choose a reason for hiding this comment

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

@rahulrajesh21 The code here looks good to me, though I am a little worried about performance implications of step down sizing, can you provide a rough timing of how long it takes to perform stepDownscale for the sample image you provided in comparison to direct one step scaling.

@rahulrajesh21
Copy link
Contributor Author

@shubham1g5 for sample image (4080 x 3060 pixels ) direct scaling is taking around 1 ms and stepDownscale is taking 16 ms. I tested it with a 4k image (3840 x 2160 pixels ) direct scaling took 1 ms and stepDownscale took 10 ms

Copy link
Contributor

@shubham1g5 shubham1g5 left a comment

Choose a reason for hiding this comment

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

@rahulrajesh21 Thanks for putting out those timings, I think that's something we should be able to live with. Left one more question for you where it would be nice to get your thoughts on.


// Final step to exactly match target dimensions
if (width != targetWidth || height != targetHeight) {
Bitmap finalBitmap = Bitmap.createScaledBitmap(currentBitmap, targetWidth, targetHeight, false);
Copy link
Contributor

Choose a reason for hiding this comment

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

I would be curious on your reasoning of putting bilinear filtering as false here and true above while wondering if it should be false even above or true even here ?

Copy link
Contributor Author

@rahulrajesh21 rahulrajesh21 May 13, 2025

Choose a reason for hiding this comment

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

@shubham1g5 Bilinear filtering is set as true to prevent visual artifacts at the cost of image quality. For the final step it is kept false to persevere image quality and reduce performance impact.

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you elaborate more on what do you mean by preventing visual artifacts and why does it not matter in the final step when it matters in the intermediary steps ?

Copy link
Contributor Author

@rahulrajesh21 rahulrajesh21 May 13, 2025

Choose a reason for hiding this comment

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

@shubham1g5 Visual artifacts like moiré patterns and stippling occur primarily when downsampling at large ratios. Bilinear filtering averages neighboring pixels, which helps smooth out these artifacts.
When reducing dimensions by large factors, the sampling grid can align improperly with high-frequency details in the original image. This causes interference patterns - similar to strange patterns in digital photos of striped fabrics. In intermediary steps, bilinear filtering helps by averaging pixels, softening these problematic interference patterns.

In the final step, these artifacts matter less because:

  1. The scaling ratio is much smaller.
  2. The major frequency mismatches that cause interference have already been addressed in previous steps.
  3. When sampling distance is smaller, the likelihood of problematic frequency interactions is reduced.

In the final step, bilinear filtering could also be kept true, but may reduce image quality and impact performance. So it is kept false to preserve sharpness and detail in the final image while maintaining better performance.

Copy link
Contributor

Choose a reason for hiding this comment

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

that's insightful, thanks for the detailed explanation here.

@shubham1g5 shubham1g5 merged commit 3636000 into dimagi:master May 13, 2025
2 checks passed
@shubham1g5 shubham1g5 added this to the 2.57 milestone May 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants