React Native Image Resizer

repository·master·Indexed 23 days ago

https://github.com/bamlab/react-native-image-resizer

A library for resizing and compressing local images in React Native applications. It supports JPEG, PNG, and WEBP formats, rotation, and metadata preservation. Compatible with both the old and new React Native architectures (Turbo Module), the library provides the createResizedImage API to handle image scaling with modes such as contain, cover, and stretch.

Tokens
2.5K
Snippets
7
Records
15
Agent score
78%

What's inside @bam.tech/react-native-image-resizer

  1. Install @bam.tech/react-native-image-resizer

    master

    To use the modern version of the library (v3.0.0+), which supports the React Native New Architecture (Turbo Module) and maintains retrocompatibility, use the following commands:

    yarn add @bam.tech/react-native-image-resizer
    cd ios && pod install

    Note: Since version 3.0.0, the package name has changed from react-native-image-resizer to @bam.tech/react-native-image-resizer.

  2. Manually link the library in Android

    master

    If you cannot use react-native link, you must manually configure the Android project by updating settings.gradle, app/build.gradle, and MainApplication.java.

    1. Update settings.gradle: Include the project and point to the directory in node_modules.
    2. Update app/build.gradle: Add the project to your dependencies block.
    3. Update MainApplication.java: Import the package and add ImageResizerPackage to your ReactInstanceManager.Builder configuration.
    #### settings.gradle
    include ':react-native-image-resizer'
    project(':react-native-image-resizer').projectDir = new File(rootProject.projectDir, '../node_modules/@bam.tech/react-native-image-resizer/android')
    
    #### app/build.gradle
    dependencies {
      ...
      implementation project(':react-native-image-resizer')
      ...
    }
    
    #### MainApplication.java
    import com.reactnativeimageresizer.ImageResizerPackage;
    
    // Inside your ReactInstanceManager.Builder configuration:
    .addPackage(new ImageResizerPackage())
  3. Known Limitations

    master

    New Architecture & Camera Roll

    If you are using @react-native-camera-roll/camera-roll with new architecture enabled, this library will not work. Attempting to display an image with the library's uri in an <Image /> component will result in: No suitable image URL loader found for ph://.... Recommendation: Use react-native-image-picker instead.

    EXIF Orientation

    Image EXIF orientation is correctly handled on Android, but not yet on iOS.

  4. Use createResizedImage to resize images

    master

    The createResizedImage method is the primary API for resizing images. It accepts a URI or path and returns a Promise that resolves with an object containing the new image's metadata.

    import ImageResizer from '@bam.tech/react-native-image-resizer';
    
    ImageResizer.createResizedImage(
      path,
      maxWidth,
      maxHeight,
      compressFormat,
      quality,
      rotation,
      outputPath
    )
      .then((response) => {
        // response.uri is the URI of the new image that can now be displayed, uploaded...
        // response.path is the path of the new image
        // response.name is the name of the new image with the extension
        // response.size is the size of the new image
      })
      .catch((err) => {
        // Handle error
      });
    import ImageResizer from '@bam.tech/react-native-image-resizer';
    
    ImageResizer.createResizedImage(
      path,
      maxWidth,
      maxHeight,
      compressFormat,
      quality,
      rotation,
      outputPath
    )
      .then((response) => {
        // response.uri is the URI of the new image that can now be displayed, uploaded...
        // response.path is the path of the new image
        // response.name is the name of the new image with the extension
        // response.size is the size of the new image
      })
      .catch((err) => {
        // Oops, something went wrong. Check that the filename is correct and
        // inspect err to get more details.
      });
  5. API Reference: createResizedImage

    master

    Resizes an image and returns a Promise resolving to an object containing: path, uri, name, size (bytes), width (pixels), and height of the new file.

    Parameters

    ParameterType/Description
    uriPath of image file, or a base64 encoded image string prefixed with data:image/imagetype (where imagetype is jpeg or png). Tested with @bam.tech/react-native-image-picker, react-native-vision-camera, @react-native-camera-roll/camera-roll and http links.
    maxWidthMaximum width for the resized image.
    maxHeightMaximum height for the resized image.
    compressFormatJPEG, PNG or WEBP (android only).
    qualityA number between 0 and 100. Used for JPEG compression.
    rotation(Default: 0) Rotation to apply in degrees (Android). On iOS, rotation is limited/rounded to multiples of 90 degrees.
    outputPathThe resized image path. If null, resized image is stored in cache folder. If setting outputPath, ensure rotation is also set (use 0 if no rotation is needed).
    keepMeta(Default: false) If true, attempts to preserve file metadata/exif info (except orientation). Only works for JPEG images loaded from the file system (not Web).
    optionsConfiguration object (see below).
  6. Configure image resizing with Options

    master

    When calling the resizer API, you can provide an Options object to control how the image is scaled and whether it should be upscaled.

    • mode: Determines how the image fits the target dimensions. Defaults to 'contain'.
      • 'contain': Fits the image within width and height while preserving the aspect ratio.
      • 'cover': Ensures at least one dimension matches the target while the other is equal to or larger than the target, preserving aspect ratio.
      • 'stretch': Resizes the image to exactly the specified width and height, potentially distorting the aspect ratio.
    • onlyScaleDown: A boolean that, if set to true, prevents the resizer from increasing the image dimensions if the target size is larger than the original. Defaults to false.
  7. Reference: createResizedImage options

    master

    The options object passed to createResizedImage contains the following keys:

    KeyDescription
    options.modeResizing mode: contain (default, preserves ratio), cover (preserves ratio, ensures image is at least width wide or height tall), or stretch (resizes exactly to width and height).
    options.onlyScaleDownIf true, the image will never be enlarged; it will only be made smaller.
  8. Resize an image with createResizedImage

    master

    The createResizedImage function allows you to resize an image from a given URI to specific dimensions, format, and quality. It supports different scaling modes and can optionally scale down only, preserve metadata, or specify a custom output path.

    Parameters:

    • uri (string): The local URI of the image to resize.
    • width (number): The target width.
    • height (number): The target height.
    • format (ResizeFormat): The desired output image format.
    • quality (number): The image quality (typically 0-100).
    • rotation (number, optional): The rotation in degrees. Defaults to 0.
    • outputPath (string | null, optional): A specific path where the resized image should be saved. If null, a default path is used.
    • keepMeta (boolean, optional): Whether to preserve image metadata. Defaults to false.
    • options (Options, optional): Configuration for scaling behavior. Defaults to { mode: 'contain', onlyScaleDown: false }.

    Returns:

    • Promise<Response>: A promise that resolves to a Response object containing the new image details (such as uri, width, height, etc.).
  9. Configure resizing behavior with Options

    master

    The Options object controls how the image is scaled during the resizing process. It is passed as the final argument to createResizedImage.

    Keys:

    • mode (ResizeMode): Determines how the image fits the target dimensions. Common values include 'contain' (default).
    • onlyScaleDown (boolean): If true, the image will only be resized if the target dimensions are smaller than the original. Defaults to false.