### Install react-native-nitro-image Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/README.md Install the library and its dependencies. Remember to run `pod install` for iOS. ```bash npm install react-native-nitro-image npm install react-native-nitro-modules cd ios && pod install ``` -------------------------------- ### Basic File Loading Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/loadimage.md A practical example of loading an image from a file path and handling potential errors. ```APIDOC ## Examples ### Basic File Loading ```typescript import { loadImage } from 'react-native-nitro-image' async function loadProfilePicture() { try { const image = await loadImage({ filePath: '/tmp/profile.jpg' }) console.log(`Loaded image: ${image.width}x${image.height}`) } catch (error) { console.error('Failed to load image:', error) } } ``` ``` -------------------------------- ### Install iOS Pods Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/example/README.md After navigating to the 'ios' directory, run this command to install or update native dependencies for iOS. ```sh bundle exec pod install ``` -------------------------------- ### Start Metro Bundler Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/example/README.md Run this command from the root of your React Native project to start the Metro dev server. ```sh bun start ``` -------------------------------- ### Loading from Multiple Sources Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md Demonstrates loading multiple images using the useImage hook within a loop. ```APIDOC ## Loading from Multiple Sources ```typescript function ImageGallery({ items }) { return items.map((item) => { const { image } = useImage(item.imageSource) return }) } ``` ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/example/README.md Run this command to install CocoaPods itself, typically needed once when setting up a new project. ```ruby bundle install ``` -------------------------------- ### Basic Usage Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md Demonstrates the basic usage of the useImage hook to load an image from a file path and display it. ```APIDOC ## Basic Usage ```typescript import { useImage } from 'react-native-nitro-image' function ProfileScreen() { const { image, error } = useImage({ filePath: '/tmp/profile.jpg' }) if (error) { return Failed to load image: {error.message} } if (!image) { return Loading image... } return Image loaded: {image.width}x{image.height} } ``` ``` -------------------------------- ### Install React Native Nitro Web Image Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/README.md Install the additional package for loading web images. Run `pod install` for iOS after installation. ```sh npm i react-native-nitro-web-image cd ios && pod install ``` -------------------------------- ### Install WebImages Package Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/webimages.md Install the react-native-nitro-web-image package using npm and run pod install for iOS. This module is optional. ```bash npm install react-native-nitro-web-image cd ios && pod install ``` -------------------------------- ### Loading from URL Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md Shows how to use the useImage hook to load an image from a URL. ```APIDOC ## Loading from URL ```typescript function ProfilePicture({ url }) { const { image, error } = useImage({ url }) if (error) { return } if (!image) { return } return } ``` ``` -------------------------------- ### Complete ThumbHash Workflow Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/imageutils.md Demonstrates the end-to-end process of generating a ThumbHash from an image, storing it, and then using it to display a placeholder while the full image loads. ```typescript import { Images, thumbHashToBase64String, thumbHashFromBase64String } from 'react-native-nitro-image' // 1. Generate ThumbHash from an image async function generateThumbHashForUser(imagePath: string): Promise { const image = await Images.loadFromFileAsync(imagePath) // Resize to small size for efficient encoding const small = await image.resizeAsync(100, 100) // Generate ThumbHash const thumbHash = await small.toThumbHashAsync() // Convert to Base64 string for storage return thumbHashToBase64String(thumbHash) } // 2. Store in database async function saveUserProfile(user: User) { const thumbHashBase64 = await generateThumbHashForUser(user.profilePicturePath) // Store in database await db.users.update(user.id, { profile_picture_thumbhash: thumbHashBase64 }) } // 3. Retrieve and display placeholder async function displayUserProfile(user: User) { // Load placeholder from stored ThumbHash if (user.profile_picture_thumbhash) { const thumbHashBuffer = thumbHashFromBase64String(user.profile_picture_thumbhash) const placeholderImage = await Images.loadFromThumbHashAsync(thumbHashBuffer) // Display placeholder while loading actual image displayImage(placeholderImage) } // Load actual image in background const actualImage = await loadImage({ url: user.profile_picture_url }) // Replace placeholder with actual image displayImage(actualImage) } ``` -------------------------------- ### Loading Multiple Image Sources Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/loadimage.md Demonstrates the flexibility of loadImage by showing how to load images from various sources in succession. ```APIDOC ### Loading Multiple Image Sources ```typescript // All of these work with loadImage const webImage = await loadImage({ url: 'https://picsum.photos/seed/123/400' }) const fileImage = await loadImage({ filePath: '/tmp/my-image.jpg' }) const resourceImage = await loadImage({ resource: 'my-image.jpg' }) const symbolImage = await loadImage({ symbolName: 'star' }) const requireImage = loadImage(require('./my-image.jpg')) ``` ``` -------------------------------- ### Dynamic Aspect Ratio Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md Illustrates how to use the useImage hook to load an image and dynamically set its aspect ratio. ```APIDOC ## Dynamic Aspect Ratio ```typescript function ResponsiveImage({ filePath }) { const { image, error } = useImage({ filePath }) const aspect = (image?.width ?? 1) / (image?.height ?? 1) if (error) { return Error loading image } return ( ) } ``` ``` -------------------------------- ### Basic File Loading Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/loadimage.md Demonstrates a typical use case for loading an image from a file path with basic error handling. ```typescript import { loadImage } from 'react-native-nitro-image' async function loadProfilePicture() { try { const image = await loadImage({ filePath: '/tmp/profile.jpg' }) console.log(`Loaded image: ${image.width}x${image.height}`) } catch (error) { console.error('Failed to load image:', error) } } ``` -------------------------------- ### Loading Images from Different Sources Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/loadimage.md Examples demonstrating how to use the loadImage function with various input types. ```APIDOC ## Input Types ### From File Path Load an image from a filesystem path: ```typescript const image = await loadImage({ filePath: '/tmp/image.jpg' }) ``` ### From URL Load an image from a URL (requires `react-native-nitro-web-image`): ```typescript const image = await loadImage({ url: 'https://example.com/image.jpg', options: { priority: 'high', cacheKey: 'custom-cache-key' } }) ``` ### From Resource Load an image from app resources: ```typescript const image = await loadImage({ resource: 'app_icon' }) ``` ### From Symbol Name Load an image from an SF Symbol (iOS only): ```typescript const image = await loadImage({ symbolName: 'star' }) ``` ### From Require Load an image from a React Native require statement: ```typescript const image = loadImage(require('./image.png')) ``` ### From Raw Pixel Data Load an image from raw pixel buffer: ```typescript const rawData: RawPixelData = { buffer: arrayBuffer, width: 100, height: 100, pixelFormat: 'RGBA' } const image = await loadImage({ rawPixelData: rawData }) ``` ### From Encoded Image Data Load an image from encoded data (JPG, PNG, etc.): ```typescript const encoded: EncodedImageData = { buffer: jpgData, width: 200, height: 200, imageFormat: 'jpg' } const image = await loadImage({ encodedImageData: encoded }) ``` ``` -------------------------------- ### Example Usage of NitroImage with ResizeMode Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/types.md Demonstrates how to use the NitroImage component with a specific resize mode and style. ```typescript ``` -------------------------------- ### Error Handling with Retry Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md Provides an example of handling errors with the useImage hook and implementing a retry mechanism. ```APIDOC ## Error Handling with Retry ```typescript function ImageWithRetry({ filePath, onRetry }) { const { image, error } = useImage({ filePath }) if (error) { return ( Failed to load. Tap to retry. ) } if (!image) { return Loading... } return } ``` ``` -------------------------------- ### Dynamic Aspect Ratio with useImage Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md This example demonstrates how to use the useImage hook to load an image and dynamically set its aspect ratio based on its dimensions for responsive rendering. ```typescript function ResponsiveImage({ filePath }) { const { image, error } = useImage({ filePath }) const aspect = (image?.width ?? 1) / (image?.height ?? 1) if (error) { return Error loading image } return ( ) } ``` -------------------------------- ### Error Handling Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/loadimage.md Illustrates a robust way to handle potential errors when loading images using a try-catch block. ```APIDOC ### Error Handling ```typescript async function safeLoadImage(source) { try { const image = await loadImage(source) return { success: true, image } } catch (error) { return { success: false, error } } } ``` ``` -------------------------------- ### Loading State Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md This state is returned while the image is being loaded. Both 'image' and 'error' are undefined. ```typescript { image: undefined, error: undefined } ``` -------------------------------- ### Different Resize Modes Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Provides examples of using the `resizeMode` prop with different values ('cover', 'contain', 'center', 'stretch') to control how the image fits within its bounds. ```APIDOC ## Different Resize Modes ```typescript function ResizeModeExample() { return ( <> ) } ``` ``` -------------------------------- ### Example AsyncImageSource Values Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/types.md Illustrates various valid ways to provide an AsyncImageSource to the NitroImage component, covering different source types. ```typescript // All of these are valid AsyncImageSource values: const sources: AsyncImageSource[] = [ { filePath: '/tmp/image.jpg' }, { url: 'https://example.com/image.jpg' }, { resource: 'app_icon' }, { symbolName: 'star' }, { rawPixelData: rawData }, { encodedImageData: encoded }, require('./image.png'), cachedImage, // Image instance cachedLoader // ImageLoader instance ] ``` -------------------------------- ### Configure Image Load Options Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/types.md Example of setting various options for web image loading, including custom cache key and enabling progressive loading. This demonstrates how to configure specific behaviors for image requests. ```typescript const options: AsyncImageLoadOptions = { priority: 'high', cacheKey: 'custom-key', scaleDownLargeImages: true, progressive: true } ``` -------------------------------- ### Run iOS App Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/example/README.md Use this command to build and run your iOS application once Metro is running and dependencies are installed. ```sh bun run ios ``` -------------------------------- ### Example Color Definitions Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/types.md Shows how to define colors using the Color interface, including fully opaque red, transparent black, and semi-transparent gray. ```typescript const red: Color = { r: 1, g: 0, b: 0 } const transparent: Color = { r: 0, g: 0, b: 0, a: 0 } const semi: Color = { r: 0.5, g: 0.5, b: 0.5, a: 0.5 } ``` -------------------------------- ### Create Blank Image Examples Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/configuration.md Shows how to create blank images with specified dimensions, alpha channel settings, and optional fill colors using the Images.createBlankImage function. Import Images from 'react-native-nitro-image'. ```typescript import { Images } from 'react-native-nitro-image' const blank = Images.createBlankImage(100, 100, true) const red = Images.createBlankImage(100, 100, true, { r: 1, g: 0, b: 0 }) const transparent = Images.createBlankImage( 100, 100, true, { r: 0, g: 0, b: 0, a: 0 } ) ``` -------------------------------- ### Create Deferred Web Image Loader Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/webimages.md Use createWebImageLoader to create a deferred ImageLoader for a given URL. This is useful when you want to load the image only when it's needed, for example, when it becomes visible. ```typescript import { WebImages } from 'react-native-nitro-web-image' import { NitroImage } from 'react-native-nitro-image' function ProfileScreen() { const loader = WebImages.createWebImageLoader( 'https://example.com/profile.jpg', { priority: 'high' } ) return ( ) } ``` -------------------------------- ### Loaded State Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md This state is returned when the image has been successfully loaded. The 'image' property contains the loaded Image instance. ```typescript { image: Image, error: undefined } ``` -------------------------------- ### Create ImageLoader from URL Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/createimageloader.md Create a WebImageLoader by providing a URL to createImageLoader. This requires the 'react-native-nitro-web-image' package to be installed. You can also specify loading priority. ```typescript const loader = createImageLoader({ url: 'https://example.com/image.jpg', options: { priority: 'high' } }) ``` -------------------------------- ### NitroImage Resize Mode Examples Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/configuration.md Demonstrates how to use the NitroImage component with different resize modes: cover, contain, center, and stretch. Ensure the NitroImage component is imported from 'react-native-nitro-image'. ```typescript import { NitroImage } from 'react-native-nitro-image' function ResizeModeDemo() { return ( <> {/* Cover: Fill view, may clip */} {/* Contain: Fit inside view, may have transparent areas */} {/* Center: Center without scaling */} {/* Stretch: Fill view, may distort aspect ratio */} ) } ``` -------------------------------- ### Conditionally Creating ImageLoaders Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/createimageloader.md Provides an example of creating an ImageLoader conditionally based on the availability of a primary URL, falling back to a secondary URL if necessary. This is useful for dynamic image loading strategies. ```typescript import { createImageLoader } from 'react-native-nitro-image' function getImageLoader(fallbackUrl: string, primaryUrl?: string) { if (primaryUrl) { return createImageLoader({ url: primaryUrl }) } return createImageLoader({ url: fallbackUrl }) } ``` -------------------------------- ### Error Handling and Retry with useImage Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md Provides an example of how to handle image loading errors using the useImage hook and implement a retry mechanism by allowing the user to tap on a message to retry loading. ```typescript function ImageWithRetry({ filePath, onRetry }) { const { image, error } = useImage({ filePath }) if (error) { return ( Failed to load. Tap to retry. ) } if (!image) { return Loading... } return } ``` -------------------------------- ### Handle Web Module Not Installed Error Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/errors.md Catch errors when attempting to load images from URLs if the web image module is not installed. Ensure react-native-nitro-web-image is installed for URL loading. ```typescript try { const image = await loadImage({ url: 'https://example.com/image.jpg' }) } catch (error) { if (error.message.includes('not installed')) { console.error('Install react-native-nitro-web-image to load from URLs') } } ``` -------------------------------- ### With Custom Loading Options Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Illustrates how to provide custom loading options, such as priority and cache keys, when loading an image from a URL. ```APIDOC ## With Custom Loading Options ```typescript function OptimizedImage({ url }) { return ( ) } ``` ``` -------------------------------- ### Error State Example Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimage.md This state is returned when an error occurred during loading. The 'error' property contains the Error object. ```typescript { image: undefined, error: Error } ``` -------------------------------- ### Enable Modular Headers for SDWebImage (iOS) Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/configuration.md For web image loading on iOS, SDWebImage requires modular headers. Add this to your Podfile. ```ruby target 'MyApp' do config = use_native_modules! # Enable modular headers for SDWebImage pod 'SDWebImage', :modular_headers => true use_react_native!(...) end ``` -------------------------------- ### All Resize Modes Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nativennitroimage.md Demonstrates the different `resizeMode` options available for NativeNitroImage: cover, contain, center, and stretch. ```APIDOC ## All Resize Modes ### Description This example showcases the four different `resizeMode` options available for the `NativeNitroImage` component: 'cover', 'contain', 'center', and 'stretch'. ### Code ```typescript function ResizeModesDemo() { const loader = createImageLoader({ url: 'https://example.com/wide-image.jpg' }) return ( <> ) } ``` ``` -------------------------------- ### With Image Instance Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nativennitroimage.md Shows how to use NativeNitroImage with a pre-loaded Image instance. ```APIDOC ## With Image Instance ### Description This example demonstrates using `NativeNitroImage` with an `Image` instance loaded directly from resources. ### Code ```typescript import { NativeNitroImage, Images } from 'react-native-nitro-image' function DirectImageDisplay() { const image = Images.loadFromResources('app_logo') return ( ) } ``` ``` -------------------------------- ### With Require Statement Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Demonstrates how to use a `require()` statement to load local assets as the image source for the NitroImage component. ```APIDOC ## With Require Statement ```typescript function LocalImage() { return ( ) } ``` ``` -------------------------------- ### Example Usage of RequireType Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/types.md Demonstrates how to use the RequireType with the loadImage function. The numeric ID obtained from require() is passed to loadImage to load the image. ```typescript const imageId = require('./image.png') // RequireType const image = loadImage(imageId) ``` -------------------------------- ### Dynamic Aspect Ratio Calculation Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Use the `useImage` hook to get image dimensions and dynamically set the `aspectRatio` style for responsive layouts. ```typescript import { useImage } from 'react-native-nitro-image' function ResponsiveImage({ filePath }) { const { image } = useImage({ filePath }) const aspect = (image?.width ?? 1) / (image?.height ?? 1) return ( ) } ``` -------------------------------- ### Load Image from URL Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/loadimage.md Load an image from a remote URL. This requires the 'react-native-nitro-web-image' package to be installed. You can also specify options like priority and cacheKey. ```typescript const image = await loadImage({ url: 'https://example.com/image.jpg', options: { priority: 'high', cacheKey: 'custom-cache-key' } }) ``` -------------------------------- ### Configure SDWebImage for Modular Headers Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/README.md Enable modular headers for SDWebImage in your app's Podfile. This is required for static linkage when using web images. ```ruby target '…' do config = use_native_modules! # Add this line: pod 'SDWebImage', :modular_headers => true end ``` -------------------------------- ### Basic Usage Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nativennitroimage.md Demonstrates the basic usage of NativeNitroImage by passing an image loaded via the `useImage` hook. ```APIDOC ## Basic Usage ### Description This example shows how to use the `NativeNitroImage` component with an image loaded using the `useImage` hook. ### Code ```typescript import { NativeNitroImage } from 'react-native-nitro-image' import { useImage } from 'react-native-nitro-image' function App() { const image = useImage({ filePath: '/tmp/image.jpg' }) return ( ) } ``` ``` -------------------------------- ### Crop Image Synchronously Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/image.md Crops an image to a new instance based on specified start and end coordinates. The coordinates can be defined using percentages of the original image dimensions. ```typescript const image = await Images.loadFromFileAsync('/tmp/image.jpg') const cropped = image.crop( image.width * 0.1, image.height * 0.1, image.width * 0.8, image.height * 0.8 ) ``` -------------------------------- ### Basic ImageLoader Creation with NitroImage Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/createimageloader.md Demonstrates how to create an ImageLoader for a local file and use it with the NitroImage component. Ensure the 'react-native-nitro-image' library is imported. ```typescript import { createImageLoader, NitroImage } from 'react-native-nitro-image' const imageLoader = createImageLoader({ filePath: '/tmp/my-image.jpg' }) function App() { return ( ) } ``` -------------------------------- ### AsyncImageLoadOptions Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/webimages.md Configuration options for web image loading. These options allow fine-grained control over how images are fetched, cached, and displayed. ```APIDOC ## AsyncImageLoadOptions Configuration options for web image loading. ### Options Table | Option | Type | Default | Description | |--------|------|---------|-------------| | priority | 'low' | 'default' | Download priority. Higher priority downloads start sooner | | forceRefresh | boolean | false | Force cache refresh even if URL is unchanged | | cacheKey | string | URL | Custom cache key for access control and custom caching | | continueInBackground | boolean | false | Allow download to continue when app is backgrounded | | allowInvalidSSLCertificates | boolean | false | Allow untrusted SSL certificates (⚠️ Use with caution) | | scaleDownLargeImages | boolean | false | Scale down images larger than device constraints (max 60MB, 4096x4096) | | queryMemoryDataSync | boolean | false | Query memory cache synchronously instead of async | | queryDiskDataSync | boolean | false | Query disk cache synchronously instead of async | | decodeImage | boolean | true | Decode image from binary. Disable to speed up, but increases memory usage | | allowHardware | boolean | true | Use hardware textures for rendering (Android only) | | progressive | boolean | false | Display image progressively as it loads, web-style (iOS only) | ``` -------------------------------- ### Images.loadFromResources Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/images.md Synchronously loads an Image from the given resource or system name. Throws an error if the image does not exist or cannot be parsed. ```APIDOC ## Images.loadFromResources ### Description Synchronously loads an Image from the given resource or system name. Throws an error if the image does not exist or cannot be parsed. ### Method Synchronous ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Required - The resource or system name of the image to load ### Returns `Image` — The loaded Image instance ### Throws - If no Image exists under the given name - If the file cannot be parsed as an Image ### Example ```typescript const appIcon = Images.loadFromResources('app_icon') ``` ``` -------------------------------- ### Handle SSL Certificate Errors with Options Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/errors.md Catch SSL certificate verification errors when loading images from URLs. Includes an example for retrying with `allowInvalidSSLCertificates: true` in development environments. ```typescript try { const image = await WebImages.loadFromURLAsync(url) } catch (error) { if (error.message.includes('SSL')) { if (__DEV__) { // Retry with SSL verification disabled return WebImages.loadFromURLAsync(url, { allowInvalidSSLCertificates: true }) } else { console.error('SSL certificate error in production') } } } ``` -------------------------------- ### Basic Usage with File Path Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Display an image using its local file path. Ensure the image is accessible on the device. ```typescript import { NitroImage } from 'react-native-nitro-image' import { View } from 'react-native' function App() { return ( ) } ``` -------------------------------- ### Basic Usage with File Path Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Demonstrates how to use the NitroImage component to display an image from a local file path. ```APIDOC ## Basic Usage with File Path ```typescript import { NitroImage } from 'react-native-nitro-image' import { View } from 'react-native' function App() { return ( ) } ``` ``` -------------------------------- ### Get Raw Pixel Data Asynchronously Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/image.md Asynchronously retrieves the raw pixel data of an image. Use this method when you need to perform pixel-level operations without blocking the UI thread. ```typescript const image = await Images.loadFromFileAsync('/tmp/image.jpg') const rawData = await image.toRawPixelDataAsync() console.log(`Image size: ${rawData.width}x${rawData.height}`) ``` -------------------------------- ### Create Blank Image Synchronously Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/images.md Use `createBlankImage` to synchronously create a new blank Image. Optionally fill it with a specified color. Ensure alpha channel is enabled if transparency is needed. ```typescript const blank = Images.createBlankImage(100, 100, true) const blankRed = Images.createBlankImage(100, 100, true, { r: 1, g: 0, b: 0 }) ``` -------------------------------- ### Implementing Retry Logic for Image Loading Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/errors.md Add retry logic to image loading to handle transient network issues. This example retries loading up to a specified number of times with increasing delays. ```typescript async function loadImageWithRetry(url: string, maxRetries: number = 3) { for (let i = 0; i < maxRetries; i++) { try { return await WebImages.loadFromURLAsync(url) } catch (error) { if (i === maxRetries - 1) { throw error } // Wait before retrying await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))) } } } ``` -------------------------------- ### Load Image from File Synchronously Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/images.md Use `loadFromFile` to synchronously load an Image from a local filesystem path. The path should include the file extension but not the `file://` prefix. This method throws errors for invalid paths or unparseable data. ```typescript const image = Images.loadFromFile('/tmp/my-image.jpg') ``` -------------------------------- ### Dynamic Image Sizing with Aspect Ratio Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/README.md Calculates and applies dynamic width and height to a `` component based on the image's aspect ratio. Uses the `useImage` hook to get image dimensions. ```tsx function App() { const { image, error } = useImage({ filePath: '/tmp/image.jpg' }) const aspect = (image?.width ?? 1) / (image?.height ?? 1) return ( ) } ``` -------------------------------- ### Feed/List Images Load Options Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/configuration.md Configure options for images displayed in feeds or lists, balancing performance and memory usage. ```typescript const options: AsyncImageLoadOptions = { priority: 'default', cacheKey: `feed-${itemId}`, queryMemoryDataSync: true } ``` -------------------------------- ### Get Raw Pixel Data from Image Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/image.md Retrieves the raw pixel data of an image as an ArrayBuffer. Useful for direct pixel manipulation or analysis. Handles different pixel formats like BGRA and ARGB. ```typescript const image = await Images.loadFromFileAsync('/tmp/image.jpg') const rawData = image.toRawPixelData() const data = new Uint8Array(rawData.buffer) let r, g, b if (rawData.pixelFormat === 'BGRA') { r = data[2] g = data[1] b = data[0] } else { r = data[0] g = data[1] b = data[2] } ``` -------------------------------- ### Basic Image Usage Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/README.md Render an image from the file system using the NitroImage component. Ensure the image path is correct. ```typescript import { NitroImage } from 'react-native-nitro-image' function App() { return ( ) } ``` -------------------------------- ### Images.loadFromFile Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/images.md Synchronously loads an Image from the given filesystem path. Throws an error if the path is invalid or data cannot be parsed. ```APIDOC ## Images.loadFromFile ### Description Synchronously loads an Image from the given filesystem path. Throws an error if the path is invalid or data cannot be parsed. ### Method Synchronous ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **filePath** (string) - Required - The filesystem path including file extension. Not a URL, don't pass `file://` prefix ### Returns `Image` — The loaded Image instance ### Throws - If the filePath is invalid - If the data cannot be parsed as an Image ### Example ```typescript const image = Images.loadFromFile('/tmp/my-image.jpg') ``` ``` -------------------------------- ### Preload Images Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/webimages.md Use `WebImages.preload` to proactively download images that will be needed soon. This is useful for critical assets like logos or headers during app startup. ```typescript import { WebImages } from 'react-native-nitro-web-image' async function initializeApp() { // Preload critical images on startup const criticalImages = [ 'https://example.com/logo.png', 'https://example.com/header.jpg' ] criticalImages.forEach(url => { WebImages.preload(url) }) } ``` -------------------------------- ### Configure NitroWebImage Android Build with CMake Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/packages/react-native-nitro-web-image/android/CMakeLists.txt Sets up the native Android library build for NitroWebImage. Includes defining the library, linking necessary modules like log and react-native-nitro-image, and setting include directories. ```cmake project(NitroWebImage) cmake_minimum_required(VERSION 3.9.0) set (PACKAGE_NAME NitroWebImage) set (CMAKE_VERBOSE_MAKEFILE ON) set (CMAKE_CXX_STANDARD 20) # Define C++ library and add all sources add_library(${PACKAGE_NAME} SHARED src/main/cpp/cpp-adapter.cpp ) # Add Nitrogen specs :) include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/NitroWebImage+autolinking.cmake) # Set up local includes include_directories( "src/main/cpp" "../cpp" ) find_library(LOG_LIB log) find_package(react-native-nitro-image REQUIRED) # <-- for the HybridImage type # Link all libraries together target_link_libraries( ${PACKAGE_NAME} ${LOG_LIB} android # <-- Android core react-native-nitro-image::NitroImage # <-- NitroImage ) ``` -------------------------------- ### Loading from Multiple Source Types Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/useimageloader.md Demonstrates the flexibility of useImageLoader in handling various asynchronous image source types, including file paths, URLs, resources, and raw pixel data. It also handles synchronous sources like `require()` statements. ```typescript function ImageLoader({ source }) { const loader = useImageLoader(source) // loader can handle: // - { filePath: '...' } → Creates FileImageLoader // - { url: '...' } → Creates WebImageLoader // - { resource: '...' } → Creates ResourceImageLoader // - { rawPixelData: ... } → Creates RawPixelDataImageLoader // - Already loaded Image → Returns as-is // - require('./image.png') → Detects and handles return ( ) } ``` -------------------------------- ### Custom Loading Options Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Configure advanced loading options such as priority, cache key, and image scaling for optimized performance. ```typescript function OptimizedImage({ url }) { return ( ) } ``` -------------------------------- ### Check and Use HEIC Writing Support Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/README.md Checks if the host OS natively supports HEIC writing and dynamically selects the format for saving an image. Requires importing `supportsHeicWriting`. ```typescript import { supportsHeicWriting } from 'react-native-nitro-modules' const image = ... const format = supportsHeicWriting ? 'heic' : 'jpg' const path = await image.saveToTemporaryFileAsync(format, 100) ``` -------------------------------- ### With ImageLoader Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nativennitroimage.md Illustrates using NativeNitroImage with an ImageLoader instance, suitable for deferred image loading. ```APIDOC ## With ImageLoader ### Description This example shows how to use `NativeNitroImage` with an `ImageLoader` instance, which is useful for loading images asynchronously. ### Code ```typescript import { NativeNitroImage, createImageLoader } from 'react-native-nitro-image' function LoaderDisplay() { const loader = createImageLoader({ filePath: '/tmp/deferred-image.jpg' }) return ( ) } ``` ``` -------------------------------- ### Creating Multiple ImageLoaders Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/createimageloader.md Shows how to create multiple ImageLoaders using different source types: URL, file path, and a named resource. This is useful for managing various images within an application. ```typescript const profilePicLoader = createImageLoader({ url: 'https://example.com/profile.jpg' }) const backgroundLoader = createImageLoader({ filePath: '/tmp/background.jpg' }) const fallbackLoader = createImageLoader({ resource: 'default_image' }) ``` -------------------------------- ### Profile Pictures Load Options Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/configuration.md Use these options for loading profile pictures, prioritizing high-quality and specific caching. ```typescript const options: AsyncImageLoadOptions = { priority: 'high', cacheKey: `profile-${userId}`, scaleDownLargeImages: true } ``` -------------------------------- ### Create Blank Image Asynchronously Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/images.md Use `createBlankImageAsync` to asynchronously create a new blank Image. This method returns a Promise that resolves to the Image instance. It also supports filling the image with a color. ```typescript const blank = await Images.createBlankImageAsync(200, 200, false) ``` -------------------------------- ### renderInto Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/image.md Renders one image onto another at a specified position and size, returning a new image. ```APIDOC ## renderInto ### Description Renders the given Image into a copy of this Image at the given position and size. ### Method Signature ```typescript renderInto(image: Image, x: number, y: number, width: number, height: number): Image ``` ### Parameters #### Path Parameters - **image** (Image) - Required - The image to render into this image. - **x** (number) - Required - The X position to render at. - **y** (number) - Required - The Y position to render at. - **width** (number) - Required - The width to scale the rendered image to. - **height** (number) - Required - The height to scale the rendered image to. ### Returns `Image` - A new Image with the rendered content. ### Example ```typescript const image1 = await Images.loadFromFileAsync('/tmp/image1.jpg') const image2 = await Images.loadFromFileAsync('/tmp/image2.jpg') const result = image1.renderInto(image2, 10, 10, 80, 80) ``` ``` -------------------------------- ### Different Resize Modes Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Demonstrates the effect of different `resizeMode` props ('cover', 'contain', 'center', 'stretch') on how an image is displayed within its bounds. ```typescript function ResizeModeExample() { return ( <> ) } ``` -------------------------------- ### Load Image from File Path Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/loadimage.md Load an image directly from a filesystem path. This is a common use case for local images. ```typescript const image = await loadImage({ filePath: '/tmp/image.jpg' }) ``` -------------------------------- ### Basic NitroImage Usage Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/README.md Demonstrates how to use the NitroImage component to display a local image. Ensure the image path is correctly specified. ```tsx function App() { return ( ) } ``` -------------------------------- ### In a FlatList with Recycling Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/nitroimage.md Shows how to efficiently use NitroImage in a `FlatList` by providing a `recyclingKey` to optimize image recycling and prevent stale images. ```APIDOC ## In a FlatList with Recycling ```typescript import { NitroImage } from 'react-native-nitro-image' import { FlatList } from 'react-native' function ImageListItem({ item }) { return ( ) } function ImageGrid({ items }) { return ( } keyExtractor={(item) => item.id} numColumns={3} /> ) } ``` ``` -------------------------------- ### Images.createBlankImage Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/images.md Synchronously creates a new blank Image of the given size. Supports filling with a specified color. ```APIDOC ## Images.createBlankImage ### Description Synchronously creates a new blank Image of the given size. Supports filling with a specified color. ### Method Synchronous ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **width** (number) - Required - The width of the new Image in pixels - **height** (number) - Required - The height of the new Image in pixels - **enableAlpha** (boolean) - Required - Whether to add an alpha channel for transparency - **fill** (Color) - Optional - If set, fill the whole image with the given color (r, g, b, a from 0.0 to 1.0) ### Returns `Image` — A new blank Image instance ### Example ```typescript const blank = Images.createBlankImage(100, 100, true) const blankRed = Images.createBlankImage(100, 100, true, { r: 1, g: 0, b: 0 }) ``` ``` -------------------------------- ### Load Image with SSL Flexibility Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/webimages.md Use `WebImages.loadFromURLAsync` with `allowInvalidSSLCertificates: true` for development or testing environments where SSL certificates might be self-signed or invalid. Use with caution. ```typescript // ⚠️ Only for development or testing const image = await WebImages.loadFromURLAsync(url, { allowInvalidSSLCertificates: true }) ``` -------------------------------- ### createWebImageLoader Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/webimages.md Creates a deferred ImageLoader that loads an Image from the given URL. This is useful for integrating with components like NitroImage that expect an ImageLoader. ```APIDOC ## createWebImageLoader ### Description Creates a deferred ImageLoader that loads an Image from the given URL. ### Method ```typescript WebImages.createWebImageLoader(url: string, options?: AsyncImageLoadOptions): ImageLoader ``` ### Parameters #### Path Parameters - **url** (string) - Required - The HTTP(S) URL of the image to load - **options** (AsyncImageLoadOptions) - Optional - Optional configuration for loading behavior ### Returns `ImageLoader` — A deferred loader that fetches the image when needed ### Example ```typescript import { WebImages } from 'react-native-nitro-web-image' import { NitroImage } from 'react-native-nitro-image' function ProfileScreen() { const loader = WebImages.createWebImageLoader( 'https://example.com/profile.jpg', { priority: 'high' } ) return ( ) } ``` ``` -------------------------------- ### renderIntoAsync Source: https://github.com/mrousavy/react-native-nitro-image/blob/main/_autodocs/api-reference/image.md Asynchronously renders one image onto another at a specified position and size, returning a new image. ```APIDOC ## renderIntoAsync ### Description Asynchronously renders the given Image into a copy of this Image. ### Method Signature ```typescript renderIntoAsync(image: Image, x: number, y: number, width: number, height: number): Promise ``` ### Parameters #### Path Parameters - **image** (Image) - Required - The image to render into this image. - **x** (number) - Required - The X position to render at. - **y** (number) - Required - The Y position to render at. - **width** (number) - Required - The width to scale the rendered image to. - **height** (number) - Required - The height to scale the rendered image to. ### Returns `Promise` - Promise resolving to a new Image with rendered content. ### Example ```typescript const image1 = await Images.loadFromFileAsync('/tmp/image1.jpg') const image2 = await Images.loadFromFileAsync('/tmp/image2.jpg') const result = await image1.renderIntoAsync(image2, 10, 10, 80, 80) ``` ```