Thanks to visit codestin.com
Credit goes to github.com

Skip to content

fix(android) handle width height as strings in image-asset #10736

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

Pastoray
Copy link

@Pastoray Pastoray commented May 2, 2025

PR Checklist

What is the current behavior?

Passing a string (e.g. "300") to width or height in ImageAssetOptions on Android results in a crash on older API levels (e.g. API 22), with the error:

IllegalArgumentException: bitmap size exceeds 32 bits

This happens because the dimensions are not parsed properly, and Android attempts to decode the image with invalid bounds.

What is the new behavior?

Ensures that width and height are explicitly parsed using parseInt() if they are strings.
Falls back to screen dimensions (Screen.mainScreen.widthPixels/heightPixels) if parsing fails.
Prevents runtime crashes.

Fixes/Implements/Closes #[6289].

Summary by CodeRabbit

  • New Features

    • Image asset configuration now supports specifying width and height as either numbers or strings for greater flexibility.
  • Bug Fixes

    • Improved handling of invalid width and height values by normalizing or removing them as needed, with warnings logged for invalid entries.
  • Chores

    • Enhanced internal logic for image size calculation and loading, providing more robust and predictable image asset behavior.

@@ -47,8 +48,30 @@ export function getAspectSafeDimensions(sourceWidth, sourceHeight, reqWidth, req
}

export function getRequestedImageSize(src: { width: number; height: number }, options: ImageAssetOptions): { width: number; height: number } {
let reqWidth = options.width || Math.min(src.width, Screen.mainScreen.widthPixels);
let reqHeight = options.height || Math.min(src.height, Screen.mainScreen.heightPixels);
const optionsCopy = { ...(this.options || {}) };
Copy link
Contributor

Choose a reason for hiding this comment

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

Thank you for the pr @Pastoray, it'd be good to have the ImageAssetOptions reflect that too and likely need to parse it on ios as well:


should be number | string

Copy link
Author

Choose a reason for hiding this comment

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

Hi @NathanWalker ,

Thanks for the quick review and feedback!

I've pushed a few updates to the PR to reflect the width?: number | string; and height?: number | string; changes in packages/core/image-asset/index.d.ts as you suggested, as well as some changes suggested by coderabitai regarding API usage and performance.

Regarding the parsing on iOS, it looks like the getRequestedImageSize function (defined in image-asset-common.ts) is already being utilized within the getImageAsync method for both Android and iOS, so i don't really get what you meant when you said "likely need to parse it on ios as well". Let me know if I've misunderstood anything!

Thanks again.

Copy link

coderabbitai bot commented May 30, 2025

"""

Walkthrough

The changes update the image asset handling logic to allow width and height options to be specified as either numbers or strings. The code now normalizes these values by parsing strings to integers and handling invalid cases. Type definitions are updated accordingly, and the Android and iOS image loading logic is adjusted to compute image dimensions using these normalized options or method calls when available.

Changes

File(s) Change Summary
packages/core/image-asset/image-asset-common.ts Enhanced getRequestedImageSize to normalize width/height from string to number, handle errors, and use sanitized options.
packages/core/image-asset/index.android.ts Updated getImageAsync to validate asset presence, compute image size with normalized options, and serialize new options for native loading.
packages/core/image-asset/index.ios.ts Modified getImageAsync to obtain image dimensions via getWidth/getHeight methods if available, else fallback to property access.
packages/core/image-asset/index.d.ts Changed ImageAssetOptions.width and height types from number to number | string.

Poem

A string or a number, both now can be,
For image width and height, in our API tree.
We parse and we check, with careful delight,
So your images load, always just right.
🖼️🐇✨
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-05-30T18_54_56_289Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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.

Copy link

@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

🔭 Outside diff range comments (1)
packages/core/image-asset/image-asset-common.ts (1)

75-79: 🛠️ Refactor suggestion

Keep aspect-ratio flag should use the sanitized copy

After the above change, optionsCopy becomes the source of truth. Using the unsanitized options object here may re-introduce invalid values (e.g. string width/height that were deleted). Safer to reference the already-cleaned copy:

-if (options && options.keepAspectRatio) {
+if (optionsCopy.keepAspectRatio) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 75-75: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🧹 Nitpick comments (3)
packages/core/image-asset/index.d.ts (1)

13-15: Document the newly-allowed string values for better DX

The union change is correct, but the interface comment / docs still imply numeric pixel values only. Consider adding a short JSDoc note (or an inline comment) that string values should contain a number in base-10 (e.g. "300"), because developers might otherwise try "300px" or "100%", which will be silently parsed or rejected at runtime.

packages/core/image-asset/image-asset-common.ts (1)

57-60: Minor: avoid delete for perf / terser output

Static-analysis is flagging the delete operator. You can sidestep the cost with an undefined assignment:

-    delete optionsCopy.width;
+    optionsCopy.width = undefined;

Same for height. Not critical, but trivially improves V8 IC stability.

Also applies to: 67-70

🧰 Tools
🪛 Biome (1.9.4)

[error] 58-58: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

packages/core/image-asset/index.android.ts (1)

28-33: Return a real Error object for failures

Currently you invoke the callback with a string:

callback(null, 'Asset cannot be found.');

Downstream code frequently does if (error) { ... } and may expect error instanceof Error. Wrap the message:

-callback(null, 'Asset cannot be found.');
+callback(null, new Error('Asset cannot be found.'));

This aligns with the image, error contract used elsewhere in the codebase.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bc887df and 82bc403.

📒 Files selected for processing (3)
  • packages/core/image-asset/image-asset-common.ts (1 hunks)
  • packages/core/image-asset/index.android.ts (2 hunks)
  • packages/core/image-asset/index.d.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/core/image-asset/index.android.ts (1)
packages/core/image-asset/image-asset-common.ts (1)
  • getRequestedImageSize (49-85)
🪛 Biome (1.9.4)
packages/core/image-asset/image-asset-common.ts

[error] 58-58: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 68-68: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (1)
packages/core/image-asset/index.android.ts (1)

38-43: optionsCopy can inherit stale string values

Because getRequestedImageSize already parsed the strings, you can simplify:

-const optionsCopy = {
-    ...this.options,
-    width: requestedSize.width,
-    height: requestedSize.height,
-};
+const optionsCopy = {
+    ...this.options,
+    width: requestedSize.width,
+    height: requestedSize.height,
+};

(If you accept the earlier fix to use optionsCopy inside getRequestedImageSize, this stays consistent.)

Comment on lines 34 to 37
const srcWidth = this.nativeImage ? this.nativeImage.size.width : Screen.mainScreen.widthPixels;
const srcHeight = this.nativeImage ? this.nativeImage.size.height : Screen.mainScreen.heightPixels;
const requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options);

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bitmap dimension retrieval may crash on Android

android.graphics.Bitmap exposes getWidth() / getHeight(), not .size.width.
Accessing .size will throw java.lang.NoSuchFieldError on many devices.

A defensive fix:

-const srcWidth = this.nativeImage ? this.nativeImage.size.width : Screen.mainScreen.widthPixels;
-const srcHeight = this.nativeImage ? this.nativeImage.size.height : Screen.mainScreen.heightPixels;
+const srcWidth = this.nativeImage
+    ? (typeof this.nativeImage.getWidth === 'function'
+        ? this.nativeImage.getWidth()
+        : this.nativeImage.size?.width)
+    : Screen.mainScreen.widthPixels;
+const srcHeight = this.nativeImage
+    ? (typeof this.nativeImage.getHeight === 'function'
+        ? this.nativeImage.getHeight()
+        : this.nativeImage.size?.height)
+    : Screen.mainScreen.heightPixels;

This guards both iOS (size.width) and Android (getWidth()) cases.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const srcWidth = this.nativeImage ? this.nativeImage.size.width : Screen.mainScreen.widthPixels;
const srcHeight = this.nativeImage ? this.nativeImage.size.height : Screen.mainScreen.heightPixels;
const requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options);
const srcWidth = this.nativeImage
? (typeof this.nativeImage.getWidth === 'function'
? this.nativeImage.getWidth()
: this.nativeImage.size?.width)
: Screen.mainScreen.widthPixels;
const srcHeight = this.nativeImage
? (typeof this.nativeImage.getHeight === 'function'
? this.nativeImage.getHeight()
: this.nativeImage.size?.height)
: Screen.mainScreen.heightPixels;
const requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options);
🤖 Prompt for AI Agents
In packages/core/image-asset/index.android.ts around lines 34 to 37, the code
incorrectly accesses bitmap dimensions using .size.width and .size.height, which
causes crashes on Android devices because android.graphics.Bitmap uses
getWidth() and getHeight() methods instead. Update the code to check if
nativeImage has getWidth and getHeight methods and use those to get dimensions
on Android; otherwise, fallback to .size.width and .size.height for iOS. This
ensures safe dimension retrieval on both platforms.

Copy link

@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 82bc403 and 14629ab.

📒 Files selected for processing (1)
  • packages/core/image-asset/image-asset-common.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/core/image-asset/image-asset-common.ts

[error] 58-58: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 68-68: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (2)
packages/core/image-asset/image-asset-common.ts (2)

50-50: Good fix: Correctly using the options parameter.

This addresses the critical issue from the previous review where this.options was incorrectly used in a free function. The function now properly uses the options parameter.


72-73:

✅ Verification successful

Verify the type casting logic with undefined values.

The logic looks correct, but ensure that the type casting (optionsCopy.width as number) properly handles the case where width/height might be undefined after invalid string parsing.

Run the following script to verify how the fallback logic behaves with undefined values:


🏁 Script executed:

#!/bin/bash
# Description: Test the behavior of the logical OR operator with undefined values

# Create a test script to verify the fallback behavior
cat > test_fallback.js << 'EOF'
// Test the fallback logic
const Screen = { mainScreen: { widthPixels: 1080, heightPixels: 1920 } };
const src = { width: 800, height: 600 };

// Test cases
const testCases = [
  { width: undefined, height: undefined },
  { width: 300, height: undefined },
  { width: undefined, height: 400 },
  { width: 300, height: 400 }
];

testCases.forEach((optionsCopy, index) => {
  const reqWidth = (optionsCopy.width) || Math.min(src.width, Screen.mainScreen.widthPixels);
  const reqHeight = (optionsCopy.height) || Math.min(src.height, Screen.mainScreen.heightPixels);
  console.log(`Test ${index + 1}: width=${optionsCopy.width}, height=${optionsCopy.height} -> reqWidth=${reqWidth}, reqHeight=${reqHeight}`);
});
EOF

# Execute the test
node test_fallback.js

Length of output: 297


Fallback logic handles undefined width/height correctly

I verified by passing undefined for optionsCopy.width/height that the expressions

const reqWidth  = (optionsCopy.width as number)  || Math.min(src.width,  Screen.mainScreen.widthPixels);
const reqHeight = (optionsCopy.height as number) || Math.min(src.height, Screen.mainScreen.heightPixels);

correctly fall back to Math.min(src.*, Screen.mainScreen.*):

• Test 1 (undefined, undefined) → reqWidth=800, reqHeight=600
• Test 2 (300, undefined) → reqWidth=300, reqHeight=600
• Test 3 (undefined, 400) → reqWidth=800, reqHeight=400
• Test 4 (300, 400) → reqWidth=300, reqHeight=400

No changes are required here.

Copy link

@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)
packages/core/image-asset/index.ios.ts (1)

4-4: Remove unused import.

The Screen import is added but not used anywhere in this file. This creates dead code and should be removed to keep the codebase clean.

-import {Screen} from "../platform";
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14629ab and f2bdff2.

📒 Files selected for processing (3)
  • packages/core/image-asset/image-asset-common.ts (1 hunks)
  • packages/core/image-asset/index.android.ts (2 hunks)
  • packages/core/image-asset/index.ios.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/image-asset/image-asset-common.ts
  • packages/core/image-asset/index.android.ts
🔇 Additional comments (1)
packages/core/image-asset/index.ios.ts (1)

40-46: Good defensive programming for cross-platform compatibility.

The updated logic properly checks for method existence before calling getWidth() and getHeight() methods, with appropriate fallbacks to property access. This defensive approach ensures compatibility across different native image implementations while maintaining backward compatibility.

The optional chaining (?.) for nativeImage.size?.width and nativeImage.size?.height is also a good safety measure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants