├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ └── 🐛-bug-report.md └── stale.yml ├── .gitignore ├── .npmignore ├── .nvmrc ├── .watchmanconfig ├── .yarnrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── android ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ └── gradle-wrapper.jar └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── reactnativeimageresizer │ │ ├── ImageResizer.java │ │ ├── ImageResizerModule.java │ │ └── ImageResizerPackage.java │ ├── newarch │ └── com │ │ └── reactnativeimageresizer │ │ └── ImageResizerSpec.java │ └── oldarch │ └── com │ └── reactnativeimageresizer │ └── ImageResizerSpec.java ├── babel.config.js ├── docs └── android_manual_config.md ├── example ├── .bundle │ └── config ├── .node-version ├── .watchmanconfig ├── Gemfile ├── android │ ├── app │ │ ├── build.gradle │ │ ├── debug.keystore │ │ ├── proguard-rules.pro │ │ └── src │ │ │ ├── debug │ │ │ ├── AndroidManifest.xml │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── reactnativeimageresizerexample │ │ │ │ └── ReactNativeFlipper.java │ │ │ ├── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── java │ │ │ │ └── com │ │ │ │ │ └── reactnativeimageresizerexample │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ └── MainApplication.java │ │ │ └── res │ │ │ │ ├── drawable │ │ │ │ └── rn_edit_text_material.xml │ │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ └── values │ │ │ │ ├── strings.xml │ │ │ │ └── styles.xml │ │ │ └── release │ │ │ └── java │ │ │ └── com │ │ │ └── reactnativeimageresizerexample │ │ │ └── ReactNativeFlipper.java │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── app.json ├── babel.config.js ├── index.js ├── ios │ ├── .xcode.env │ ├── File.swift │ ├── Podfile │ ├── Podfile.lock │ ├── ReactNativeImageResizerExample-Bridging-Header.h │ ├── ReactNativeImageResizerExample.xcodeproj │ │ ├── project.pbxproj │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── ReactNativeImageResizerExample.xcscheme │ ├── ReactNativeImageResizerExample.xcworkspace │ │ └── contents.xcworkspacedata │ ├── ReactNativeImageResizerExample │ │ ├── AppDelegate.h │ │ ├── AppDelegate.mm │ │ ├── Images.xcassets │ │ │ ├── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Info.plist │ │ ├── LaunchScreen.storyboard │ │ └── main.m │ └── ReactNativeImageResizerExampleTests │ │ ├── Info.plist │ │ └── ReactNativeImageResizerExampleTests.m ├── metro.config.js ├── package.json ├── react-native.config.js ├── src │ └── App.tsx └── yarn.lock ├── ios ├── ImageHelpers.h ├── ImageHelpers.m ├── ImageResizer.h ├── ImageResizer.mm └── ImageResizer.xcodeproj │ └── project.pbxproj ├── lefthook.yml ├── package.json ├── react-native-image-resizer.podspec ├── scripts └── bootstrap.js ├── src ├── NativeImageResizer.ts ├── __tests__ │ └── index.test.tsx ├── index.tsx └── types.ts ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | end_of_line = lf 13 | charset = utf-8 14 | trim_trailing_whitespace = true 15 | insert_final_newline = true 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/🐛-bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F41B Bug report" 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Observed behavior** 21 | A clear and concise description of what you observed. 22 | 23 | **Expected behavior** 24 | A clear and concise description of what you expected to happen. 25 | 26 | **Screenshots** 27 | If applicable, add screenshots to help explain your problem. 28 | 29 | **Platform concerned:** 30 | - Device: [e.g. iPhone6] 31 | - OS: [e.g. iOS8.1] 32 | 33 | **Additional context** 34 | Add any other context about the problem here. 35 | 36 | **Link to reproducible example** 37 | https://..... 38 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | 4 | # Number of days of inactivity before a stale issue is closed 5 | daysUntilClose: 7 6 | 7 | # Issues or PullRequest with these labels will never be considered stale 8 | exemptLabels: 9 | - security 10 | - bug 11 | 12 | # Label to use when marking an issue as stale 13 | staleLabel: wontfix 14 | 15 | pulls: 16 | markComment: > 17 | This pull request has been automatically marked as stale because it has not had 18 | recent activity. It will be closed if no further activity occurs. Thank you 19 | for your contributions. 20 | closeComment: > 21 | This pull request has been automatically closed. Thank you 22 | for your contributions. 23 | 24 | issues: 25 | markComment: > 26 | This issue has been automatically marked as stale because it has not had 27 | recent activity. It will be closed if no further activity occurs. Thank you 28 | for your contributions. 29 | closeComment: > 30 | This issue has been automatically closed. Thank you 31 | for your contributions. 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .classpath 35 | .cxx 36 | .gradle 37 | .idea 38 | .project 39 | .settings 40 | local.properties 41 | android.iml 42 | 43 | # Cocoapods 44 | # 45 | example/ios/Pods 46 | 47 | # Ruby 48 | example/vendor/ 49 | 50 | # node.js 51 | # 52 | node_modules/ 53 | npm-debug.log 54 | yarn-debug.log 55 | yarn-error.log 56 | 57 | # BUCK 58 | buck-out/ 59 | \.buckd/ 60 | android/app/libs 61 | android/keystores/debug.keystore 62 | 63 | # Expo 64 | .expo/ 65 | 66 | # Turborepo 67 | .turbo/ 68 | 69 | # generated by bob 70 | lib/ 71 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | example 2 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 16.18.1 2 | -------------------------------------------------------------------------------- /.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /.yarnrc: -------------------------------------------------------------------------------- 1 | # Override Yarn command so we can automatically setup the repo on running `yarn` 2 | 3 | yarn-path "scripts/bootstrap.js" 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. 4 | 5 | ## Development workflow 6 | 7 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package: 8 | 9 | ```sh 10 | yarn 11 | ``` 12 | 13 | > While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development. 14 | 15 | While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app. 16 | 17 | To start the packager: 18 | 19 | ```sh 20 | yarn example start 21 | ``` 22 | 23 | To run the example app on Android: 24 | 25 | ```sh 26 | yarn example android 27 | ``` 28 | 29 | To run the example app on iOS: 30 | 31 | ```sh 32 | yarn example ios 33 | ``` 34 | 35 | 36 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 37 | 38 | ```sh 39 | yarn typescript 40 | yarn lint 41 | ``` 42 | 43 | To fix formatting errors, run the following: 44 | 45 | ```sh 46 | yarn lint --fix 47 | ``` 48 | 49 | Remember to add tests for your change if possible. Run the unit tests by: 50 | 51 | ```sh 52 | yarn test 53 | ``` 54 | To edit the Objective-C files, open `example/ios/ImageResizerExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-image-resizer`. 55 | 56 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativeimageresizer` under `Android`. 57 | ### Commit message convention 58 | 59 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 60 | 61 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 62 | - `feat`: new features, e.g. add new method to the module. 63 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 64 | - `docs`: changes into documentation, e.g. add usage example for the module.. 65 | - `test`: adding or updating tests, e.g. add integration tests using detox. 66 | - `chore`: tooling changes, e.g. change CI config. 67 | 68 | Our pre-commit hooks verify that your commit message matches this format when committing. 69 | 70 | ### Linting and tests 71 | 72 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 73 | 74 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. 75 | 76 | Our pre-commit hooks verify that the linter and tests pass when committing. 77 | 78 | ### Publishing to npm 79 | 80 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc. 81 | 82 | To publish new versions, run the following: 83 | 84 | ```sh 85 | yarn release 86 | ``` 87 | 88 | ### Scripts 89 | 90 | The `package.json` file contains various scripts for common tasks: 91 | 92 | - `yarn bootstrap`: setup project by installing all dependencies and pods. 93 | - `yarn typescript`: type-check files with TypeScript. 94 | - `yarn lint`: lint files with ESLint. 95 | - `yarn test`: run unit tests with Jest. 96 | - `yarn example start`: start the Metro server for the example app. 97 | - `yarn example android`: run the example app on Android. 98 | - `yarn example ios`: run the example app on iOS. 99 | 100 | ### Sending a pull request 101 | 102 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github). 103 | 104 | When you're sending a pull request: 105 | 106 | - Prefer small pull requests focused on one change. 107 | - Verify that linters and tests are passing. 108 | - Review the documentation to make sure it looks good. 109 | - Follow the pull request template when opening a pull request. 110 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 111 | 112 | ## Code of Conduct 113 | 114 | ### Our Pledge 115 | 116 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 117 | 118 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 119 | 120 | ### Our Standards 121 | 122 | Examples of behavior that contributes to a positive environment for our community include: 123 | 124 | - Demonstrating empathy and kindness toward other people 125 | - Being respectful of differing opinions, viewpoints, and experiences 126 | - Giving and gracefully accepting constructive feedback 127 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 128 | - Focusing on what is best not just for us as individuals, but for the overall community 129 | 130 | Examples of unacceptable behavior include: 131 | 132 | - The use of sexualized language or imagery, and sexual attention or 133 | advances of any kind 134 | - Trolling, insulting or derogatory comments, and personal or political attacks 135 | - Public or private harassment 136 | - Publishing others' private information, such as a physical or email 137 | address, without their explicit permission 138 | - Other conduct which could reasonably be considered inappropriate in a 139 | professional setting 140 | 141 | ### Enforcement Responsibilities 142 | 143 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 144 | 145 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 146 | 147 | ### Scope 148 | 149 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 150 | 151 | ### Enforcement 152 | 153 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. 154 | 155 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 156 | 157 | ### Enforcement Guidelines 158 | 159 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 160 | 161 | #### 1. Correction 162 | 163 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 164 | 165 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 166 | 167 | #### 2. Warning 168 | 169 | **Community Impact**: A violation through a single incident or series of actions. 170 | 171 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 172 | 173 | #### 3. Temporary Ban 174 | 175 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 176 | 177 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 178 | 179 | #### 4. Permanent Ban 180 | 181 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 182 | 183 | **Consequence**: A permanent ban from any sort of public interaction within the community. 184 | 185 | ### Attribution 186 | 187 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 188 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 189 | 190 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 191 | 192 | [homepage]: https://www.contributor-covenant.org 193 | 194 | For answers to common questions about this code of conduct, see the FAQ at 195 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 196 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Clément Taboulot 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Native Image Resizer 2 | 3 | > **⚠ Warning** 4 | > Since version 3.0.0 this library has been moved from `react-native-image-resizer` to `@bam.tech/react-native-image-resizer` 5 | 6 | ## Setup 7 | 8 | ### React Native >= 0.61 9 | 10 | Since the version version `3.0.0` this package support the new architecture out of the box (Turbo Module). 11 | It also has retrocompatibility with the old one. 12 | 13 | ``` 14 | yarn add @bam.tech/react-native-image-resizer 15 | cd ios && pod install 16 | ``` 17 | 18 | ### React Native <= 0.60 19 | 20 | ``` 21 | yarn add react-native-image-resizer@1.1.0 22 | cd ios && pod install 23 | ``` 24 | 25 | ### Android 26 | 27 | Note: on latest versions of React Native, you may have an error during the Gradle build on Android (`com.android.dex.DexException: Multiple dex files define Landroid/support/v7/appcompat/R$anim`). Run `cd android && ./gradlew clean` to fix this. 28 | 29 | #### Manual linking 30 | 31 | Manual link information for Android: [Link](docs/android_manual_config.md) 32 | 33 | ## Usage example 34 | 35 | ```javascript 36 | import ImageResizer from '@bam.tech/react-native-image-resizer'; 37 | 38 | ImageResizer.createResizedImage( 39 | path, 40 | maxWidth, 41 | maxHeight, 42 | compressFormat, 43 | quality, 44 | rotation, 45 | outputPath 46 | ) 47 | .then((response) => { 48 | // response.uri is the URI of the new image that can now be displayed, uploaded... 49 | // response.path is the path of the new image 50 | // response.name is the name of the new image with the extension 51 | // response.size is the size of the new image 52 | }) 53 | .catch((err) => { 54 | // Oops, something went wrong. Check that the filename is correct and 55 | // inspect err to get more details. 56 | }); 57 | ``` 58 | 59 | ### Sample app 60 | 61 | A basic, sample app is available in [the `example` folder](https://github.com/bamlab/react-native-image-resizer/tree/master/example). It uses the module to resize a photo from the Camera Roll. 62 | 63 | ## API 64 | 65 | ```javascript 66 | createResizedImage( 67 | /** 68 | * uri parameter accepts`path` or `uri`. 69 | * This property has been tested with the output of @bam.tech/react-native-image-picker, 70 | * react-native-vision-camera, @react-native-camera-roll/camera-roll and http link 71 | **/ 72 | uri, 73 | maxWidth, 74 | maxHeight, 75 | compressFormat, 76 | quality, 77 | (rotation = 0), 78 | outputPath, 79 | (keepMeta = false), 80 | (options = {}) 81 | ); // Returns a Promise 82 | ``` 83 | 84 | The promise resolves with an object containing: `path`, `uri`, `name`, `size` (bytes), `width` (pixels), and `height` of the new file. The URI can be used directly as the `source` of an [``](https://facebook.github.io/react-native/docs/image.html) component. 85 | 86 | | Option | Description | 87 | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 88 | | path | Path of image file, or a base64 encoded image string prefixed with 'data:image/imagetype' where `imagetype` is jpeg or png. | 89 | | width | Width to resize to (see `mode` for more details) | 90 | | height | Height to resize to (see `mode` for more details) | 91 | | compressFormat | Can be either JPEG, PNG or WEBP (android only). | 92 | | quality | A number between 0 and 100. Used for the JPEG compression. | 93 | | rotation | Rotation to apply to the image, in degrees, for android. On iOS, rotation is limited (and rounded) to multiples of 90 degrees. | 94 | | outputPath | The resized image path. If null, resized image will be stored in cache folder. To set outputPath make sure to add option for rotation too (if no rotation is needed, just set it to 0). | 95 | | keepMeta | If `true`, will attempt to preserve all file metadata/exif info, except the orientation value since the resizing also does rotation correction to the original image. Defaults to `false`, which means all metadata is lost. Note: This can only be `true` for `JPEG` images which are loaded from the file system (not Web). | 96 | | options.mode | Similar to [react-native Image's resizeMode](https://reactnative.dev/docs/image#resizemode): either `contain` (the default), `cover`, or `stretch`. `contain` will fit the image within `width` and `height`, preserving its ratio. `cover` preserves the aspect ratio, and makes sure the image is at least `width` wide or `height` tall. `stretch` will resize the image to exactly `width` and `height`. | 97 | | options.onlyScaleDown | If `true`, will never enlarge the image, and will only make it smaller. | 98 | 99 | # Limitations 100 | 101 | - If you are using `@react-native-camera-roll/camera-roll` **with new architecture enabled this library is not going to work**. If you try to display an image with the `uri` of the library using `` you are going to have the following error: `No suitable image URL loader found for ph://...`. This error come from the ReactNative `ImageLoader`, which is the one we are currently using. Help/PR for solving this are welcome. Until then, we recommend using `react-native-image-picker`. 102 | - Image EXIF orientation are correctly handled on Android only, But not yet on IOS [#402](https://github.com/bamlab/react-native-image-resizer/issues/402). 103 | 104 | ## 👉 About Bam 105 | 106 | We are a 100 people company developing and designing multiplatform applications with [React Native](https://www.bam.tech/agence-react-native-paris) using the Lean & Agile methodology. To get more information on the solutions that would suit your needs, feel free to get in touch by [email](mailto://contact@bam.tech) or through or [contact form](https://www.bam.tech/en/contact)! 107 | 108 | We will always answer you with pleasure 😁 109 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | 7 | dependencies { 8 | classpath "com.android.tools.build:gradle:7.2.1" 9 | 10 | } 11 | } 12 | 13 | def isNewArchitectureEnabled() { 14 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true" 15 | } 16 | 17 | apply plugin: "com.android.library" 18 | 19 | 20 | def appProject = rootProject.allprojects.find { it.plugins.hasPlugin('com.android.application') } 21 | 22 | if (isNewArchitectureEnabled()) { 23 | apply plugin: "com.facebook.react" 24 | } 25 | 26 | def getExtOrDefault(name) { 27 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["ImageResizer_" + name] 28 | } 29 | 30 | def getExtOrIntegerDefault(name) { 31 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["ImageResizer_" + name]).toInteger() 32 | } 33 | 34 | android { 35 | compileSdkVersion getExtOrIntegerDefault("compileSdkVersion") 36 | def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION 37 | def agpMajorVersion = agpVersion.tokenize('.')[0].toInteger() 38 | def agpMinorVersion = agpVersion.tokenize('.')[1].toInteger() 39 | /** 40 | * Namespace should be declared here starting from AGP 8.x, Starting AGP 7.3 it is also supported. 41 | * For AGP < 7.3, namespace should be declared in AndroidManifest. 42 | * See: https://developer.android.com/build/releases/past-releases/agp-8-0-0-release-notes#namespace-dsl 43 | */ 44 | if (agpMajorVersion >= 7 && agpMinorVersion >= 3) { 45 | namespace "com.reactnativeimageresizer" 46 | } 47 | 48 | defaultConfig { 49 | minSdkVersion getExtOrIntegerDefault("minSdkVersion") 50 | targetSdkVersion getExtOrIntegerDefault("targetSdkVersion") 51 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() 52 | } 53 | buildTypes { 54 | release { 55 | minifyEnabled false 56 | } 57 | } 58 | 59 | lintOptions { 60 | disable "GradleCompatible" 61 | } 62 | 63 | compileOptions { 64 | sourceCompatibility JavaVersion.VERSION_1_8 65 | targetCompatibility JavaVersion.VERSION_1_8 66 | } 67 | 68 | sourceSets { 69 | main { 70 | if (isNewArchitectureEnabled()) { 71 | java.srcDirs += [ 72 | "src/newarch", 73 | // This is needed to build Kotlin project with NewArch enabled 74 | "${project.buildDir}/generated/source/codegen/java" 75 | ] 76 | } else { 77 | java.srcDirs += ["src/oldarch"] 78 | } 79 | } 80 | } 81 | } 82 | 83 | repositories { 84 | mavenCentral() 85 | google() 86 | } 87 | 88 | 89 | dependencies { 90 | // For < 0.71, this will be from the local maven repo 91 | // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin 92 | //noinspection GradleDynamicVersion 93 | implementation "com.facebook.react:react-native:+" 94 | implementation "androidx.exifinterface:exifinterface:1.3.2" 95 | } 96 | 97 | if (isNewArchitectureEnabled()) { 98 | react { 99 | jsRootDir = file("../src/") 100 | libraryName = "ImageResizer" 101 | codegenJavaPackageName = "com.reactnativeimageresizer" 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | ImageResizer_kotlinVersion=1.7.0 2 | ImageResizer_minSdkVersion=21 3 | ImageResizer_targetSdkVersion=31 4 | ImageResizer_compileSdkVersion=31 5 | ImageResizer_ndkversion=21.4.7075529 6 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativeimageresizer/ImageResizer.java: -------------------------------------------------------------------------------- 1 | package com.reactnativeimageresizer; 2 | 3 | import android.content.Context; 4 | import android.content.ContentResolver; 5 | import android.database.Cursor; 6 | import android.graphics.Bitmap; 7 | import android.graphics.BitmapFactory; 8 | import android.graphics.Matrix; 9 | import androidx.exifinterface.media.ExifInterface; 10 | import android.net.Uri; 11 | import android.os.Build; 12 | import android.provider.MediaStore; 13 | import android.util.Base64; 14 | import android.util.Log; 15 | 16 | import java.io.ByteArrayOutputStream; 17 | import java.io.File; 18 | import java.io.FileOutputStream; 19 | import java.io.InputStream; 20 | import java.io.IOException; 21 | import java.net.HttpURLConnection; 22 | import java.net.URL; 23 | import java.util.Date; 24 | 25 | /** 26 | * Provide methods to resize and rotate an image file. 27 | */ 28 | public class ImageResizer { 29 | private final static String IMAGE_JPEG = "image/jpeg"; 30 | private final static String IMAGE_PNG = "image/png"; 31 | private final static String SCHEME_DATA = "data"; 32 | private final static String SCHEME_CONTENT = "content"; 33 | private final static String SCHEME_FILE = "file"; 34 | private final static String SCHEME_HTTP = "http"; 35 | private final static String SCHEME_HTTPS = "https"; 36 | 37 | 38 | // List of known EXIF tags we will be copying. 39 | // Orientation, width, height, and some others are ignored 40 | // TODO: Find any missing tag that might be useful 41 | private final static String[] EXIF_TO_COPY_ROTATED = new String[] 42 | { 43 | ExifInterface.TAG_APERTURE_VALUE, 44 | ExifInterface.TAG_MAX_APERTURE_VALUE, 45 | ExifInterface.TAG_METERING_MODE, 46 | ExifInterface.TAG_ARTIST, 47 | ExifInterface.TAG_BITS_PER_SAMPLE, 48 | ExifInterface.TAG_COMPRESSION, 49 | ExifInterface.TAG_BODY_SERIAL_NUMBER, 50 | ExifInterface.TAG_BRIGHTNESS_VALUE, 51 | ExifInterface.TAG_CONTRAST, 52 | ExifInterface.TAG_CAMERA_OWNER_NAME, 53 | ExifInterface.TAG_COLOR_SPACE, 54 | ExifInterface.TAG_COPYRIGHT, 55 | ExifInterface.TAG_DATETIME, 56 | ExifInterface.TAG_DATETIME_DIGITIZED, 57 | ExifInterface.TAG_DATETIME_ORIGINAL, 58 | ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION, 59 | ExifInterface.TAG_DIGITAL_ZOOM_RATIO, 60 | ExifInterface.TAG_EXIF_VERSION, 61 | ExifInterface.TAG_EXPOSURE_BIAS_VALUE, 62 | ExifInterface.TAG_EXPOSURE_INDEX, 63 | ExifInterface.TAG_EXPOSURE_MODE, 64 | ExifInterface.TAG_EXPOSURE_TIME, 65 | ExifInterface.TAG_EXPOSURE_PROGRAM, 66 | ExifInterface.TAG_FLASH, 67 | ExifInterface.TAG_FLASH_ENERGY, 68 | ExifInterface.TAG_FOCAL_LENGTH, 69 | ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM, 70 | ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT, 71 | ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION, 72 | ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION, 73 | ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION, 74 | ExifInterface.TAG_PLANAR_CONFIGURATION, 75 | ExifInterface.TAG_F_NUMBER, 76 | ExifInterface.TAG_GAIN_CONTROL, 77 | ExifInterface.TAG_GAMMA, 78 | ExifInterface.TAG_GPS_ALTITUDE, 79 | ExifInterface.TAG_GPS_ALTITUDE_REF, 80 | ExifInterface.TAG_GPS_AREA_INFORMATION, 81 | ExifInterface.TAG_GPS_DATESTAMP, 82 | ExifInterface.TAG_GPS_DOP, 83 | ExifInterface.TAG_GPS_LATITUDE, 84 | ExifInterface.TAG_GPS_LATITUDE_REF, 85 | ExifInterface.TAG_GPS_LONGITUDE, 86 | ExifInterface.TAG_GPS_LONGITUDE_REF, 87 | ExifInterface.TAG_GPS_STATUS, 88 | ExifInterface.TAG_GPS_DEST_BEARING, 89 | ExifInterface.TAG_GPS_DEST_BEARING_REF, 90 | ExifInterface.TAG_GPS_DEST_DISTANCE, 91 | ExifInterface.TAG_GPS_DEST_DISTANCE_REF, 92 | ExifInterface.TAG_GPS_DEST_LATITUDE, 93 | ExifInterface.TAG_GPS_DEST_LATITUDE_REF, 94 | ExifInterface.TAG_GPS_DEST_LONGITUDE, 95 | ExifInterface.TAG_GPS_DEST_LONGITUDE_REF, 96 | ExifInterface.TAG_GPS_DIFFERENTIAL, 97 | ExifInterface.TAG_GPS_IMG_DIRECTION, 98 | ExifInterface.TAG_GPS_IMG_DIRECTION_REF, 99 | ExifInterface.TAG_GPS_MAP_DATUM, 100 | ExifInterface.TAG_GPS_MEASURE_MODE, 101 | ExifInterface.TAG_GPS_PROCESSING_METHOD, 102 | ExifInterface.TAG_GPS_SATELLITES, 103 | ExifInterface.TAG_GPS_SPEED, 104 | ExifInterface.TAG_GPS_SPEED_REF, 105 | ExifInterface.TAG_GPS_STATUS, 106 | ExifInterface.TAG_GPS_TIMESTAMP, 107 | ExifInterface.TAG_GPS_TRACK, 108 | ExifInterface.TAG_GPS_TRACK_REF, 109 | ExifInterface.TAG_GPS_VERSION_ID, 110 | ExifInterface.TAG_IMAGE_DESCRIPTION, 111 | ExifInterface.TAG_IMAGE_UNIQUE_ID, 112 | ExifInterface.TAG_ISO_SPEED, 113 | ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY, 114 | ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT, 115 | ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 116 | ExifInterface.TAG_LENS_MAKE, 117 | ExifInterface.TAG_LENS_MODEL, 118 | ExifInterface.TAG_LENS_SERIAL_NUMBER, 119 | ExifInterface.TAG_LENS_SPECIFICATION, 120 | ExifInterface.TAG_LIGHT_SOURCE, 121 | ExifInterface.TAG_MAKE, 122 | ExifInterface.TAG_MAKER_NOTE, 123 | ExifInterface.TAG_MODEL, 124 | // ExifInterface.TAG_ORIENTATION, // removed 125 | ExifInterface.TAG_SATURATION, 126 | ExifInterface.TAG_SHARPNESS, 127 | ExifInterface.TAG_SHUTTER_SPEED_VALUE, 128 | ExifInterface.TAG_SOFTWARE, 129 | ExifInterface.TAG_SUBJECT_DISTANCE, 130 | ExifInterface.TAG_SUBJECT_DISTANCE_RANGE, 131 | ExifInterface.TAG_SUBJECT_LOCATION, 132 | ExifInterface.TAG_USER_COMMENT, 133 | ExifInterface.TAG_WHITE_BALANCE 134 | }; 135 | 136 | 137 | 138 | /** 139 | * Resize the specified bitmap. 140 | */ 141 | private static Bitmap resizeImage(Bitmap image, int newWidth, int newHeight, 142 | String mode, boolean onlyScaleDown) { 143 | Bitmap newImage = null; 144 | if (image == null) { 145 | return null; // Can't load the image from the given path. 146 | } 147 | 148 | int width = image.getWidth(); 149 | int height = image.getHeight(); 150 | 151 | if (newHeight > 0 && newWidth > 0) { 152 | int finalWidth; 153 | int finalHeight; 154 | 155 | if (mode.equals("stretch")) { 156 | // Distort aspect ratio 157 | finalWidth = newWidth; 158 | finalHeight = newHeight; 159 | 160 | if (onlyScaleDown) { 161 | finalWidth = Math.min(width, finalWidth); 162 | finalHeight = Math.min(height, finalHeight); 163 | } 164 | } else { 165 | // "contain" (default) or "cover": keep its aspect ratio 166 | float widthRatio = (float) newWidth / width; 167 | float heightRatio = (float) newHeight / height; 168 | 169 | float ratio = mode.equals("cover") ? 170 | Math.max(widthRatio, heightRatio) : 171 | Math.min(widthRatio, heightRatio); 172 | 173 | if (onlyScaleDown) ratio = Math.min(ratio, 1); 174 | 175 | finalWidth = (int) Math.round(width * ratio); 176 | finalHeight = (int) Math.round(height * ratio); 177 | } 178 | 179 | try { 180 | newImage = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true); 181 | } catch (OutOfMemoryError e) { 182 | return null; 183 | } 184 | } 185 | 186 | return newImage; 187 | } 188 | 189 | /** 190 | * Rotate the specified bitmap with the given angle, in degrees. 191 | */ 192 | public static Bitmap rotateImage(Bitmap source, Matrix matrix, float angle) 193 | { 194 | Bitmap retVal; 195 | matrix.postRotate(angle); 196 | 197 | try { 198 | retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); 199 | } catch (OutOfMemoryError e) { 200 | return null; 201 | } 202 | return retVal; 203 | } 204 | 205 | /** 206 | * Save the given bitmap in a directory. Extension is automatically generated using the bitmap format. 207 | */ 208 | public static File saveImage(Bitmap bitmap, File saveDirectory, String fileName, 209 | Bitmap.CompressFormat compressFormat, int quality) 210 | throws IOException { 211 | if (bitmap == null) { 212 | throw new IOException("The bitmap couldn't be resized"); 213 | } 214 | 215 | File newFile = new File(saveDirectory, fileName + "." + compressFormat.name()); 216 | if(!newFile.createNewFile()) { 217 | throw new IOException("The file already exists"); 218 | } 219 | 220 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 221 | bitmap.compress(compressFormat, quality, outputStream); 222 | byte[] bitmapData = outputStream.toByteArray(); 223 | 224 | outputStream.flush(); 225 | outputStream.close(); 226 | 227 | FileOutputStream fos = new FileOutputStream(newFile); 228 | fos.write(bitmapData); 229 | fos.flush(); 230 | fos.close(); 231 | 232 | return newFile; 233 | } 234 | 235 | /** 236 | * Get {@link File} object for the given Android URI.
237 | * Use content resolver to get real path if direct path doesn't return valid file. 238 | */ 239 | private static File getFileFromUri(Context context, Uri uri) { 240 | 241 | // first try by direct path 242 | File file = new File(uri.getPath()); 243 | if (file.exists()) { 244 | return file; 245 | } 246 | 247 | // try reading real path from content resolver (gallery images) 248 | Cursor cursor = null; 249 | try { 250 | String[] proj = {MediaStore.Images.Media.DATA}; 251 | cursor = context.getContentResolver().query(uri, proj, null, null, null); 252 | int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 253 | cursor.moveToFirst(); 254 | String realPath = cursor.getString(column_index); 255 | file = new File(realPath); 256 | } catch (Exception ignored) { 257 | } finally { 258 | if (cursor != null) { 259 | cursor.close(); 260 | } 261 | } 262 | 263 | return file; 264 | } 265 | 266 | /** 267 | * Attempts to copy exif info from one file to another. Note: orientation, width, and height 268 | exif attributes are not copied since those are lost after image rotation. 269 | 270 | * imageUri: original image URI as provided from JS 271 | * dstPath: final image output path 272 | * Returns true if copy was successful, false otherwise. 273 | */ 274 | public static boolean copyExif(Context context, Uri imageUri, String dstPath){ 275 | ExifInterface src = null; 276 | ExifInterface dst = null; 277 | 278 | try { 279 | 280 | File file = getFileFromUri(context, imageUri); 281 | if (!file.exists()) { 282 | return false; 283 | } 284 | 285 | src = new ExifInterface(file.getAbsolutePath()); 286 | dst = new ExifInterface(dstPath); 287 | 288 | } catch (Exception ignored) { 289 | Log.e("ImageResizer::copyExif", "EXIF read failed", ignored); 290 | } 291 | 292 | if(src == null || dst == null){ 293 | return false; 294 | } 295 | 296 | try{ 297 | 298 | for (String attr : EXIF_TO_COPY_ROTATED) 299 | { 300 | String value = src.getAttribute(attr); 301 | if (value != null){ 302 | dst.setAttribute(attr, value); 303 | } 304 | } 305 | dst.saveAttributes(); 306 | 307 | } catch (Exception ignored) { 308 | Log.e("ImageResizer::copyExif", "EXIF copy failed", ignored); 309 | return false; 310 | } 311 | 312 | return true; 313 | } 314 | 315 | /** 316 | * Get orientation by reading Image metadata 317 | */ 318 | public static Matrix getOrientationMatrix(Context context, Uri uri) { 319 | try { 320 | // ExifInterface(InputStream) only exists since Android N (r24) 321 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 322 | InputStream input = context.getContentResolver().openInputStream(uri); 323 | ExifInterface ei = new ExifInterface(input); 324 | return getOrientationMatrix(ei); 325 | } 326 | File file = getFileFromUri(context, uri); 327 | if (file.exists()) { 328 | ExifInterface ei = new ExifInterface(file.getAbsolutePath()); 329 | return getOrientationMatrix(ei); 330 | } 331 | } catch (Exception ignored) { } 332 | 333 | return new Matrix(); 334 | } 335 | 336 | /** 337 | * Convert metadata to degrees 338 | */ 339 | public static Matrix getOrientationMatrix(ExifInterface exif) { 340 | Matrix matrix = new Matrix(); 341 | int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); 342 | switch (orientation) { 343 | case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: 344 | matrix.setScale(-1, 1); 345 | break; 346 | case ExifInterface.ORIENTATION_TRANSPOSE: 347 | matrix.setRotate(90); 348 | matrix.postScale(-1, 1); 349 | break; 350 | case ExifInterface.ORIENTATION_ROTATE_90: 351 | matrix.setRotate(90); 352 | break; 353 | case ExifInterface.ORIENTATION_FLIP_VERTICAL: 354 | matrix.setRotate(180); 355 | matrix.postScale(-1, 1); 356 | break; 357 | case ExifInterface.ORIENTATION_ROTATE_180: 358 | matrix.setRotate(180); 359 | break; 360 | case ExifInterface.ORIENTATION_TRANSVERSE: 361 | matrix.setRotate(270); 362 | matrix.postScale(-1, 1); 363 | break; 364 | case ExifInterface.ORIENTATION_ROTATE_270: 365 | matrix.setRotate(270); 366 | break; 367 | } 368 | return matrix; 369 | } 370 | 371 | /** 372 | * Compute the inSampleSize value to use to load a bitmap. 373 | * Adapted from https://developer.android.com/training/displaying-bitmaps/load-bitmap.html 374 | */ 375 | private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 376 | final int height = options.outHeight; 377 | final int width = options.outWidth; 378 | 379 | int inSampleSize = 1; 380 | 381 | if (height > reqHeight || width > reqWidth) { 382 | final int halfHeight = height / 2; 383 | final int halfWidth = width / 2; 384 | 385 | // Calculate the largest inSampleSize value that is a power of 2 and keeps both 386 | // height and width larger than the requested height and width. 387 | while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { 388 | inSampleSize *= 2; 389 | } 390 | } 391 | 392 | return inSampleSize; 393 | } 394 | 395 | /** 396 | * Load a bitmap either from a real file or using the {@link ContentResolver} of the current 397 | * {@link Context} (to read gallery images for example). 398 | * 399 | * Note that, when options.inJustDecodeBounds = true, we actually expect sourceImage to remain 400 | * as null (see https://developer.android.com/training/displaying-bitmaps/load-bitmap.html), so 401 | * getting null sourceImage at the completion of this method is not always worthy of an error. 402 | */ 403 | private static Bitmap loadBitmap(Context context, Uri imageUri, BitmapFactory.Options options) throws IOException { 404 | Bitmap sourceImage = null; 405 | String imageUriScheme = imageUri.getScheme(); 406 | if (imageUriScheme == null || !imageUriScheme.equalsIgnoreCase(SCHEME_CONTENT)) { 407 | try { 408 | sourceImage = BitmapFactory.decodeFile(imageUri.getPath(), options); 409 | } catch (Exception e) { 410 | e.printStackTrace(); 411 | throw new IOException("Error decoding image file"); 412 | } 413 | } else { 414 | ContentResolver cr = context.getContentResolver(); 415 | InputStream input = cr.openInputStream(imageUri); 416 | if (input != null) { 417 | sourceImage = BitmapFactory.decodeStream(input, null, options); 418 | input.close(); 419 | } 420 | } 421 | return sourceImage; 422 | } 423 | 424 | /** 425 | * Loads the bitmap resource from the file specified in imagePath. 426 | */ 427 | private static Bitmap loadBitmapFromFile(Context context, Uri imageUri, int newWidth, 428 | int newHeight) throws IOException { 429 | // Decode the image bounds to find the size of the source image. 430 | BitmapFactory.Options options = new BitmapFactory.Options(); 431 | options.inJustDecodeBounds = true; 432 | loadBitmap(context, imageUri, options); 433 | 434 | // Set a sample size according to the image size to lower memory usage. 435 | options.inSampleSize = calculateInSampleSize(options, newWidth, newHeight); 436 | options.inJustDecodeBounds = false; 437 | //System.out.println(options.inSampleSize); 438 | return loadBitmap(context, imageUri, options); 439 | 440 | } 441 | 442 | /** 443 | * Loads the bitmap resource from an URL 444 | */ 445 | private static Bitmap loadBitmapFromURL(Uri imageUri, int newWidth, 446 | int newHeight) throws IOException { 447 | 448 | InputStream input = null; 449 | Bitmap sourceImage = null; 450 | 451 | try{ 452 | URL url = new URL(imageUri.toString()); 453 | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 454 | connection.connect(); 455 | input = connection.getInputStream(); 456 | 457 | if (input != null) { 458 | 459 | // need to load into memory since inputstream is not seekable 460 | // we still won't load the whole bitmap into memory 461 | // Also need this ugly code since we are on Java8... 462 | ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 463 | int nRead; 464 | byte[] data = new byte[1024]; 465 | byte[] imageData = null; 466 | 467 | try{ 468 | while ((nRead = input.read(data, 0, data.length)) != -1) { 469 | buffer.write(data, 0, nRead); 470 | } 471 | buffer.flush(); 472 | imageData = buffer.toByteArray(); 473 | } 474 | finally{ 475 | buffer.close(); 476 | } 477 | 478 | 479 | // Decode the image bounds to find the size of the source image. 480 | // Do it here so we only do one request 481 | BitmapFactory.Options options = new BitmapFactory.Options(); 482 | options.inJustDecodeBounds = true; 483 | BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options); 484 | 485 | // Set a sample size according to the image size to lower memory usage. 486 | options.inSampleSize = calculateInSampleSize(options, newWidth, newHeight); 487 | options.inJustDecodeBounds = false; 488 | 489 | sourceImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options); 490 | } 491 | } 492 | catch (Exception e) { 493 | e.printStackTrace(); 494 | throw new IOException("Error fetching remote image file."); 495 | } 496 | finally{ 497 | try { 498 | if(input != null){ 499 | input.close(); 500 | } 501 | } 502 | catch (IOException e) { 503 | e.printStackTrace(); 504 | } 505 | 506 | } 507 | 508 | return sourceImage; 509 | 510 | } 511 | 512 | /** 513 | * Loads the bitmap resource from a base64 encoded jpg or png. 514 | * Format is as such: 515 | * png: 'data:image/png;base64,iVBORw0KGgoAA...' 516 | * jpg: 'data:image/jpeg;base64,/9j/4AAQSkZJ...' 517 | */ 518 | private static Bitmap loadBitmapFromBase64(Uri imageUri) { 519 | Bitmap sourceImage = null; 520 | String imagePath = imageUri.getSchemeSpecificPart(); 521 | int commaLocation = imagePath.indexOf(','); 522 | if (commaLocation != -1) { 523 | final String mimeType = imagePath.substring(0, commaLocation).replace('\\','/').toLowerCase(); 524 | final boolean isJpeg = mimeType.startsWith(IMAGE_JPEG); 525 | final boolean isPng = !isJpeg && mimeType.startsWith(IMAGE_PNG); 526 | 527 | if (isJpeg || isPng) { 528 | // base64 image. Convert to a bitmap. 529 | final String encodedImage = imagePath.substring(commaLocation + 1); 530 | final byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT); 531 | sourceImage = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 532 | } 533 | } 534 | 535 | return sourceImage; 536 | } 537 | 538 | /** 539 | * Create a resized version of the given image and returns a Bitmap object 540 | * ready to be saved or converted. Ensure that the result is cleaned up after use 541 | * by using recycle 542 | */ 543 | public static Bitmap createResizedImage(Context context, Uri imageUri, int newWidth, 544 | int newHeight, int quality, int rotation, 545 | String mode, boolean onlyScaleDown) throws IOException { 546 | Bitmap sourceImage = null; 547 | String imageUriScheme = imageUri.getScheme(); 548 | 549 | if (imageUriScheme == null || 550 | imageUriScheme.equalsIgnoreCase(SCHEME_FILE) || 551 | imageUriScheme.equalsIgnoreCase(SCHEME_CONTENT) 552 | ) { 553 | sourceImage = ImageResizer.loadBitmapFromFile(context, imageUri, newWidth, newHeight); 554 | } else if (imageUriScheme.equalsIgnoreCase(SCHEME_HTTP) || imageUriScheme.equalsIgnoreCase(SCHEME_HTTPS)){ 555 | sourceImage = ImageResizer.loadBitmapFromURL(imageUri, newWidth, newHeight); 556 | } else if (imageUriScheme.equalsIgnoreCase(SCHEME_DATA)) { 557 | sourceImage = ImageResizer.loadBitmapFromBase64(imageUri); 558 | } 559 | 560 | if (sourceImage == null) { 561 | throw new IOException("Unable to load source image from path"); 562 | } 563 | 564 | 565 | // Rotate if necessary. Rotate first because we will otherwise 566 | // get wrong dimensions if we want the new dimensions to be after rotation. 567 | // NOTE: This will "fix" the image using it's exif info if it is rotated as well. 568 | Bitmap rotatedImage = sourceImage; 569 | Matrix matrix = getOrientationMatrix(context, imageUri); 570 | rotatedImage = ImageResizer.rotateImage(sourceImage, matrix, rotation); 571 | 572 | if(rotatedImage == null){ 573 | throw new IOException("Unable to rotate image. Most likely due to not enough memory."); 574 | } 575 | 576 | if (rotatedImage != sourceImage) { 577 | sourceImage.recycle(); 578 | } 579 | 580 | // Scale image 581 | Bitmap scaledImage = ImageResizer.resizeImage(rotatedImage, newWidth, newHeight, mode, onlyScaleDown); 582 | 583 | if(scaledImage == null){ 584 | throw new IOException("Unable to resize image. Most likely due to not enough memory."); 585 | } 586 | 587 | if (scaledImage != rotatedImage) { 588 | rotatedImage.recycle(); 589 | } 590 | 591 | return scaledImage; 592 | } 593 | } 594 | 595 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativeimageresizer/ImageResizerModule.java: -------------------------------------------------------------------------------- 1 | package com.reactnativeimageresizer; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.graphics.Bitmap; 5 | import android.net.Uri; 6 | import android.os.AsyncTask; 7 | import android.util.Log; 8 | 9 | import androidx.annotation.Nullable; 10 | import androidx.annotation.NonNull; 11 | 12 | import com.facebook.react.bridge.Arguments; 13 | import com.facebook.react.bridge.GuardedAsyncTask; 14 | import com.facebook.react.bridge.Promise; 15 | import com.facebook.react.bridge.ReactApplicationContext; 16 | import com.facebook.react.bridge.ReadableMap; 17 | import com.facebook.react.bridge.WritableMap; 18 | import com.facebook.react.bridge.ReactMethod; 19 | 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | import java.util.UUID; 24 | 25 | public class ImageResizerModule extends ImageResizerSpec { 26 | public static final String NAME = "ImageResizer"; 27 | 28 | ImageResizerModule(ReactApplicationContext reactContext) { 29 | super(reactContext); 30 | } 31 | 32 | @Override 33 | @NonNull 34 | public String getName() { 35 | return NAME; 36 | } 37 | 38 | @ReactMethod 39 | public void createResizedImage(String uri, double width, double height, String format, double quality, String mode, boolean onlyScaleDown, Double rotation, @Nullable String outputPath, Boolean keepMeta, Promise promise) { 40 | WritableMap options = Arguments.createMap(); 41 | options.putString("mode", mode); 42 | options.putBoolean("onlyScaleDown", onlyScaleDown); 43 | 44 | // Run in guarded async task to prevent blocking the React bridge 45 | new GuardedAsyncTask(this.getReactApplicationContext()) { 46 | @Override 47 | protected void doInBackgroundGuarded(Void... params) { 48 | try { 49 | Object response = createResizedImageWithExceptions(uri, (int) width, (int) height, format, (int) quality, rotation.intValue(), outputPath, keepMeta, options); 50 | promise.resolve(response); 51 | } 52 | catch (IOException e) { 53 | promise.reject(e); 54 | } 55 | } 56 | }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 57 | } 58 | 59 | @SuppressLint("LongLogTag") 60 | private Object createResizedImageWithExceptions(String imagePath, int newWidth, int newHeight, 61 | String compressFormatString, int quality, int rotation, String outputPath, 62 | final boolean keepMeta, 63 | final ReadableMap options) throws IOException { 64 | 65 | Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.valueOf(compressFormatString); 66 | Uri imageUri = Uri.parse(imagePath); 67 | 68 | Bitmap scaledImage = ImageResizer.createResizedImage(this.getReactApplicationContext(), imageUri, newWidth, newHeight, quality, rotation, 69 | options.getString("mode"), options.getBoolean("onlyScaleDown")); 70 | 71 | if (scaledImage == null) { 72 | throw new IOException("The image failed to be resized; invalid Bitmap result."); 73 | } 74 | 75 | // Save the resulting image 76 | File path = this.getReactApplicationContext().getCacheDir(); 77 | if (outputPath != null) { 78 | path = new File(outputPath); 79 | } 80 | 81 | File resizedImage = ImageResizer.saveImage(scaledImage, path, UUID.randomUUID().toString(), compressFormat, quality); 82 | WritableMap response = Arguments.createMap(); 83 | 84 | // If resizedImagePath is empty and this wasn't caught earlier, throw. 85 | if (resizedImage.isFile()) { 86 | response.putString("path", resizedImage.getAbsolutePath()); 87 | response.putString("uri", Uri.fromFile(resizedImage).toString()); 88 | response.putString("name", resizedImage.getName()); 89 | response.putDouble("size", resizedImage.length()); 90 | response.putDouble("width", scaledImage.getWidth()); 91 | response.putDouble("height", scaledImage.getHeight()); 92 | 93 | // Copy file's metadata/exif info if required 94 | if(keepMeta){ 95 | try{ 96 | ImageResizer.copyExif(this.getReactApplicationContext(), imageUri, resizedImage.getAbsolutePath()); 97 | } 98 | catch(Exception ignored){ 99 | Log.e("ImageResizer::createResizedImageWithExceptions", "EXIF copy failed", ignored); 100 | } 101 | } 102 | } else { 103 | throw new IOException("Error getting resized image path"); 104 | } 105 | 106 | 107 | // Clean up bitmap 108 | scaledImage.recycle(); 109 | return response; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativeimageresizer/ImageResizerPackage.java: -------------------------------------------------------------------------------- 1 | package com.reactnativeimageresizer; 2 | 3 | import androidx.annotation.Nullable; 4 | import com.facebook.react.bridge.NativeModule; 5 | import com.facebook.react.bridge.ReactApplicationContext; 6 | import com.facebook.react.module.model.ReactModuleInfo; 7 | import com.facebook.react.module.model.ReactModuleInfoProvider; 8 | import com.facebook.react.TurboReactPackage; 9 | 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | public class ImageResizerPackage extends TurboReactPackage { 15 | 16 | @Nullable 17 | @Override 18 | public NativeModule getModule(String name, ReactApplicationContext reactContext) { 19 | if (name.equals(ImageResizerModule.NAME)) { 20 | return new ImageResizerModule(reactContext); 21 | } else { 22 | return null; 23 | } 24 | } 25 | 26 | @Override 27 | public ReactModuleInfoProvider getReactModuleInfoProvider() { 28 | return () -> { 29 | final Map moduleInfos = new HashMap<>(); 30 | boolean isTurboModule = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; 31 | moduleInfos.put( 32 | ImageResizerModule.NAME, 33 | new ReactModuleInfo( 34 | ImageResizerModule.NAME, 35 | ImageResizerModule.NAME, 36 | false, // canOverrideExistingModule 37 | false, // needsEagerInit 38 | true, // hasConstants 39 | false, // isCxxModule 40 | isTurboModule // isTurboModule 41 | )); 42 | return moduleInfos; 43 | }; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /android/src/newarch/com/reactnativeimageresizer/ImageResizerSpec.java: -------------------------------------------------------------------------------- 1 | package com.reactnativeimageresizer; 2 | 3 | import com.facebook.react.bridge.ReactApplicationContext; 4 | 5 | abstract class ImageResizerSpec extends NativeImageResizerSpec { 6 | ImageResizerSpec(ReactApplicationContext context) { 7 | super(context); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /android/src/oldarch/com/reactnativeimageresizer/ImageResizerSpec.java: -------------------------------------------------------------------------------- 1 | package com.reactnativeimageresizer; 2 | 3 | import androidx.annotation.Nullable; 4 | 5 | import com.facebook.react.bridge.Promise; 6 | import com.facebook.react.bridge.ReactApplicationContext; 7 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 8 | 9 | abstract class ImageResizerSpec extends ReactContextBaseJavaModule { 10 | 11 | ImageResizerSpec(ReactApplicationContext context) { 12 | super(context); 13 | } 14 | 15 | public abstract void createResizedImage(String uri, double width, double height, String format, double quality, String mode, boolean onlyScaleDown, Double rotation, @Nullable String outputPath, Boolean keepMeta, Promise promise); 16 | } 17 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /docs/android_manual_config.md: -------------------------------------------------------------------------------- 1 | #### Manual linking 2 | If your any reason you don want to link this project using 'react-native link', go to settings.gradle and add 3 | ``` 4 | include ':react-native-image-resizer' 5 | project(':react-native-image-resizer').projectDir = new File(rootProject.projectDir, '../node_modules/@bam.tech/react-native-image-resizer/android') 6 | ``` 7 | 8 | Add project to your `app/build.gradle` file 9 | ``` 10 | dependencies { 11 | ... 12 | implementation project(':react-native-image-resizer') 13 | ... 14 | } 15 | ``` 16 | 17 | import it at the top of your `MainApplication.java` file 18 | ``` 19 | import com.reactnativeimageresizer.ImageResizerPackage; 20 | ``` 21 | 22 | then go the file that you build the ReactInstance and add the packager to it. 23 | 24 | ``` 25 | ReactInstanceManager.Builder builder = ReactInstanceManager.builder() 26 | .setApplication(application) 27 | .setDefaultHardwareBackBtnHandler(application.getGAMActivity()) 28 | .setInitialLifecycleState(LifecycleState.RESUMED) 29 | .setCurrentActivity((Activity) application.getGAMActivity()) 30 | .addPackage(new RealmReactPackage()) 31 | .addPackage(new MainReactPackageWrapper()) 32 | .addPackage(new StoreReactNativePackage()) 33 | .addPackage(new ImageResizerPackage()) <------- (Add this package on the Builder list) 34 | .addPackage(gamCommunicationReactPackage); 35 | ``` 36 | -------------------------------------------------------------------------------- /example/.bundle/config: -------------------------------------------------------------------------------- 1 | BUNDLE_PATH: "vendor/bundle" 2 | BUNDLE_FORCE_RUBY_PLATFORM: 1 3 | -------------------------------------------------------------------------------- /example/.node-version: -------------------------------------------------------------------------------- 1 | 18 2 | -------------------------------------------------------------------------------- /example/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /example/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version 4 | ruby '>= 2.6.10' 5 | 6 | gem 'cocoapods', '>= 1.11.3' 7 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | apply plugin: "com.facebook.react" 3 | 4 | import com.android.build.OutputFile 5 | 6 | /** 7 | * This is the configuration block to customize your React Native Android app. 8 | * By default you don't need to apply any configuration, just uncomment the lines you need. 9 | */ 10 | react { 11 | /* Folders */ 12 | // The root of your project, i.e. where "package.json" lives. Default is '..' 13 | // root = file("../") 14 | // The folder where the react-native NPM package is. Default is ../node_modules/react-native 15 | // reactNativeDir = file("../node_modules/react-native") 16 | // The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen 17 | // codegenDir = file("../node_modules/react-native-codegen") 18 | // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js 19 | // cliFile = file("../node_modules/react-native/cli.js") 20 | 21 | /* Variants */ 22 | // The list of variants to that are debuggable. For those we're going to 23 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'. 24 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. 25 | // debuggableVariants = ["liteDebug", "prodDebug"] 26 | 27 | /* Bundling */ 28 | // A list containing the node command and its flags. Default is just 'node'. 29 | // nodeExecutableAndArgs = ["node"] 30 | // 31 | // The command to run when bundling. By default is 'bundle' 32 | // bundleCommand = "ram-bundle" 33 | // 34 | // The path to the CLI configuration file. Default is empty. 35 | // bundleConfig = file(../rn-cli.config.js) 36 | // 37 | // The name of the generated asset file containing your JS bundle 38 | // bundleAssetName = "MyApplication.android.bundle" 39 | // 40 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' 41 | // entryFile = file("../js/MyApplication.android.js") 42 | // 43 | // A list of extra flags to pass to the 'bundle' commands. 44 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle 45 | // extraPackagerArgs = [] 46 | 47 | /* Hermes Commands */ 48 | // The hermes compiler command to run. By default it is 'hermesc' 49 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" 50 | // 51 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" 52 | // hermesFlags = ["-O", "-output-source-map"] 53 | } 54 | 55 | /** 56 | * Set this to true to create four separate APKs instead of one, 57 | * one for each native architecture. This is useful if you don't 58 | * use App Bundles (https://developer.android.com/guide/app-bundle/) 59 | * and want to have separate APKs to upload to the Play Store. 60 | */ 61 | def enableSeparateBuildPerCPUArchitecture = false 62 | 63 | /** 64 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode. 65 | */ 66 | def enableProguardInReleaseBuilds = false 67 | 68 | /** 69 | * The preferred build flavor of JavaScriptCore (JSC) 70 | * 71 | * For example, to use the international variant, you can use: 72 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` 73 | * 74 | * The international variant includes ICU i18n library and necessary data 75 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that 76 | * give correct results when using with locales other than en-US. Note that 77 | * this variant is about 6MiB larger per architecture than default. 78 | */ 79 | def jscFlavor = 'org.webkit:android-jsc:+' 80 | 81 | /** 82 | * Private function to get the list of Native Architectures you want to build. 83 | * This reads the value from reactNativeArchitectures in your gradle.properties 84 | * file and works together with the --active-arch-only flag of react-native run-android. 85 | */ 86 | def reactNativeArchitectures() { 87 | def value = project.getProperties().get("reactNativeArchitectures") 88 | return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"] 89 | } 90 | 91 | android { 92 | ndkVersion rootProject.ext.ndkVersion 93 | 94 | compileSdkVersion rootProject.ext.compileSdkVersion 95 | 96 | namespace "com.reactnativeimageresizerexample" 97 | defaultConfig { 98 | applicationId "com.reactnativeimageresizerexample" 99 | minSdkVersion rootProject.ext.minSdkVersion 100 | targetSdkVersion rootProject.ext.targetSdkVersion 101 | versionCode 1 102 | versionName "1.0" 103 | } 104 | 105 | splits { 106 | abi { 107 | reset() 108 | enable enableSeparateBuildPerCPUArchitecture 109 | universalApk false // If true, also generate a universal APK 110 | include (*reactNativeArchitectures()) 111 | } 112 | } 113 | signingConfigs { 114 | debug { 115 | storeFile file('debug.keystore') 116 | storePassword 'android' 117 | keyAlias 'androiddebugkey' 118 | keyPassword 'android' 119 | } 120 | } 121 | buildTypes { 122 | debug { 123 | signingConfig signingConfigs.debug 124 | } 125 | release { 126 | // Caution! In production, you need to generate your own keystore file. 127 | // see https://reactnative.dev/docs/signed-apk-android. 128 | signingConfig signingConfigs.debug 129 | minifyEnabled enableProguardInReleaseBuilds 130 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 131 | } 132 | } 133 | 134 | // applicationVariants are e.g. debug, release 135 | applicationVariants.all { variant -> 136 | variant.outputs.each { output -> 137 | // For each separate APK per architecture, set a unique version code as described here: 138 | // https://developer.android.com/studio/build/configure-apk-splits.html 139 | // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc. 140 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] 141 | def abi = output.getFilter(OutputFile.ABI) 142 | if (abi != null) { // null for the universal-debug, universal-release variants 143 | output.versionCodeOverride = 144 | defaultConfig.versionCode * 1000 + versionCodes.get(abi) 145 | } 146 | 147 | } 148 | } 149 | } 150 | 151 | dependencies { 152 | // The version of react-native is set by the React Native Gradle Plugin 153 | implementation("com.facebook.react:react-android") 154 | 155 | implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0") 156 | 157 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") 158 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { 159 | exclude group:'com.squareup.okhttp3', module:'okhttp' 160 | } 161 | 162 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") 163 | if (hermesEnabled.toBoolean()) { 164 | implementation("com.facebook.react:hermes-android") 165 | } else { 166 | implementation jscFlavor 167 | } 168 | } 169 | 170 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) 171 | -------------------------------------------------------------------------------- /example/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/debug.keystore -------------------------------------------------------------------------------- /example/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /example/android/app/src/debug/java/com/reactnativeimageresizerexample/ReactNativeFlipper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * 4 | *

This source code is licensed under the MIT license found in the LICENSE file in the root 5 | * directory of this source tree. 6 | */ 7 | package com.reactnativeimageresizerexample; 8 | 9 | import android.content.Context; 10 | import com.facebook.flipper.android.AndroidFlipperClient; 11 | import com.facebook.flipper.android.utils.FlipperUtils; 12 | import com.facebook.flipper.core.FlipperClient; 13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; 14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; 15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; 16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping; 17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; 18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; 19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; 20 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; 21 | import com.facebook.react.ReactInstanceEventListener; 22 | import com.facebook.react.ReactInstanceManager; 23 | import com.facebook.react.bridge.ReactContext; 24 | import com.facebook.react.modules.network.NetworkingModule; 25 | import okhttp3.OkHttpClient; 26 | 27 | /** 28 | * Class responsible of loading Flipper inside your React Native application. This is the debug 29 | * flavor of it. Here you can add your own plugins and customize the Flipper setup. 30 | */ 31 | public class ReactNativeFlipper { 32 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { 33 | if (FlipperUtils.shouldEnableFlipper(context)) { 34 | final FlipperClient client = AndroidFlipperClient.getInstance(context); 35 | 36 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); 37 | client.addPlugin(new DatabasesFlipperPlugin(context)); 38 | client.addPlugin(new SharedPreferencesFlipperPlugin(context)); 39 | client.addPlugin(CrashReporterPlugin.getInstance()); 40 | 41 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); 42 | NetworkingModule.setCustomClientBuilder( 43 | new NetworkingModule.CustomClientBuilder() { 44 | @Override 45 | public void apply(OkHttpClient.Builder builder) { 46 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); 47 | } 48 | }); 49 | client.addPlugin(networkFlipperPlugin); 50 | client.start(); 51 | 52 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized 53 | // Hence we run if after all native modules have been initialized 54 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); 55 | if (reactContext == null) { 56 | reactInstanceManager.addReactInstanceEventListener( 57 | new ReactInstanceEventListener() { 58 | @Override 59 | public void onReactContextInitialized(ReactContext reactContext) { 60 | reactInstanceManager.removeReactInstanceEventListener(this); 61 | reactContext.runOnNativeModulesQueueThread( 62 | new Runnable() { 63 | @Override 64 | public void run() { 65 | client.addPlugin(new FrescoFlipperPlugin()); 66 | } 67 | }); 68 | } 69 | }); 70 | } else { 71 | client.addPlugin(new FrescoFlipperPlugin()); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | 11 | 18 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/reactnativeimageresizerexample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.reactnativeimageresizerexample; 2 | 3 | import com.facebook.react.ReactActivity; 4 | import com.facebook.react.ReactActivityDelegate; 5 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; 6 | import com.facebook.react.defaults.DefaultReactActivityDelegate; 7 | 8 | public class MainActivity extends ReactActivity { 9 | 10 | /** 11 | * Returns the name of the main component registered from JavaScript. This is used to schedule 12 | * rendering of the component. 13 | */ 14 | @Override 15 | protected String getMainComponentName() { 16 | return "ReactNativeImageResizerExample"; 17 | } 18 | 19 | /** 20 | * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link 21 | * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React 22 | * (aka React 18) with two boolean flags. 23 | */ 24 | @Override 25 | protected ReactActivityDelegate createReactActivityDelegate() { 26 | return new DefaultReactActivityDelegate( 27 | this, 28 | getMainComponentName(), 29 | // If you opted-in for the New Architecture, we enable the Fabric Renderer. 30 | DefaultNewArchitectureEntryPoint.getFabricEnabled(), // fabricEnabled 31 | // If you opted-in for the New Architecture, we enable Concurrent React (i.e. React 18). 32 | DefaultNewArchitectureEntryPoint.getConcurrentReactEnabled() // concurrentRootEnabled 33 | ); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/reactnativeimageresizerexample/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.reactnativeimageresizerexample; 2 | 3 | import android.app.Application; 4 | import com.facebook.react.PackageList; 5 | import com.facebook.react.ReactApplication; 6 | import com.facebook.react.ReactNativeHost; 7 | import com.facebook.react.ReactPackage; 8 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; 9 | import com.facebook.react.defaults.DefaultReactNativeHost; 10 | import com.facebook.soloader.SoLoader; 11 | import java.util.List; 12 | 13 | public class MainApplication extends Application implements ReactApplication { 14 | 15 | private final ReactNativeHost mReactNativeHost = 16 | new DefaultReactNativeHost(this) { 17 | @Override 18 | public boolean getUseDeveloperSupport() { 19 | return BuildConfig.DEBUG; 20 | } 21 | 22 | @Override 23 | protected List getPackages() { 24 | @SuppressWarnings("UnnecessaryLocalVariable") 25 | List packages = new PackageList(this).getPackages(); 26 | // Packages that cannot be autolinked yet can be added manually here, for example: 27 | // packages.add(new MyReactNativePackage()); 28 | return packages; 29 | } 30 | 31 | @Override 32 | protected String getJSMainModuleName() { 33 | return "index"; 34 | } 35 | 36 | @Override 37 | protected boolean isNewArchEnabled() { 38 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; 39 | } 40 | 41 | @Override 42 | protected Boolean isHermesEnabled() { 43 | return BuildConfig.IS_HERMES_ENABLED; 44 | } 45 | }; 46 | 47 | @Override 48 | public ReactNativeHost getReactNativeHost() { 49 | return mReactNativeHost; 50 | } 51 | 52 | @Override 53 | public void onCreate() { 54 | super.onCreate(); 55 | SoLoader.init(this, /* native exopackage */ false); 56 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { 57 | // If you opted-in for the New Architecture, we load the native entry point for this app. 58 | DefaultNewArchitectureEntryPoint.load(); 59 | } 60 | ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/rn_edit_text_material.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 21 | 22 | 23 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ReactNativeImageResizerExample 3 | 4 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /example/android/app/src/release/java/com/reactnativeimageresizerexample/ReactNativeFlipper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * 4 | *

This source code is licensed under the MIT license found in the LICENSE file in the root 5 | * directory of this source tree. 6 | */ 7 | package com.reactnativeimageresizerexample; 8 | 9 | import android.content.Context; 10 | import com.facebook.react.ReactInstanceManager; 11 | 12 | /** 13 | * Class responsible of loading Flipper inside your React Native application. This is the release 14 | * flavor of it so it's empty as we don't want to load Flipper. 15 | */ 16 | public class ReactNativeFlipper { 17 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { 18 | // Do nothing as we don't want to initialize Flipper on Release. 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = "33.0.0" 6 | minSdkVersion = 21 7 | compileSdkVersion = 33 8 | targetSdkVersion = 33 9 | kotlinVersion = "1.6.20" 10 | 11 | // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP. 12 | ndkVersion = "23.1.7779620" 13 | } 14 | repositories { 15 | google() 16 | mavenCentral() 17 | } 18 | dependencies { 19 | classpath("com.android.tools.build:gradle:7.3.1") 20 | classpath("com.facebook.react:react-native-gradle-plugin") 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m 13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Version of flipper SDK to use with React Native 28 | FLIPPER_VERSION=0.125.0 29 | 30 | # Use this property to specify which architecture you want to build. 31 | # You can also override it from the CLI using 32 | # ./gradlew -PreactNativeArchitectures=x86_64 33 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 34 | 35 | # Use this property to enable support to the new architecture. 36 | # This will allow you to use TurboModules and the Fabric render in 37 | # your application. You should enable this flag either if you want 38 | # to write custom TurboModules/Fabric components OR use libraries that 39 | # are providing them. 40 | newArchEnabled=true 41 | 42 | # Use this property to enable or disable the Hermes JS engine. 43 | # If set to false, you will be using JSC instead. 44 | hermesEnabled=true 45 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bamlab/react-native-image-resizer/d085f0652257d780b643da5e99369451d6a48330/example/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /example/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /example/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'ReactNativeImageResizerExample' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app' 4 | includeBuild('../node_modules/react-native-gradle-plugin') 5 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ReactNativeImageResizerExample", 3 | "displayName": "ReactNativeImageResizerExample" 4 | } -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = { 5 | presets: ['module:metro-react-native-babel-preset'], 6 | plugins: [ 7 | [ 8 | 'module-resolver', 9 | { 10 | extensions: ['.tsx', '.ts', '.js', '.json'], 11 | alias: { 12 | [pak.name]: path.join(__dirname, '..', pak.source), 13 | }, 14 | }, 15 | ], 16 | ], 17 | }; 18 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import { AppRegistry } from 'react-native'; 2 | import App from './src/App'; 3 | import { name as appName } from './app.json'; 4 | 5 | AppRegistry.registerComponent(appName, () => App); 6 | -------------------------------------------------------------------------------- /example/ios/.xcode.env: -------------------------------------------------------------------------------- 1 | # This `.xcode.env` file is versioned and is used to source the environment 2 | # used when running script phases inside Xcode. 3 | # To customize your local environment, you can create an `.xcode.env.local` 4 | # file that is not versioned. 5 | 6 | # NODE_BINARY variable contains the PATH to the node executable. 7 | # 8 | # Customize the NODE_BINARY variable here. 9 | # For example, to use nvm with brew, add the following line 10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use 11 | export NODE_BINARY=$(command -v node) 12 | -------------------------------------------------------------------------------- /example/ios/File.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // ReactNativeImageResizerExample 4 | // 5 | 6 | import Foundation 7 | -------------------------------------------------------------------------------- /example/ios/Podfile: -------------------------------------------------------------------------------- 1 | require_relative '../node_modules/react-native/scripts/react_native_pods' 2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' 3 | 4 | platform :ios, min_ios_version_supported 5 | prepare_react_native_project! 6 | 7 | # If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set. 8 | # because `react-native-flipper` depends on (FlipperKit,...) that will be excluded 9 | # 10 | # To fix this you can also exclude `react-native-flipper` using a `react-native.config.js` 11 | # ```js 12 | # module.exports = { 13 | # dependencies: { 14 | # ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}), 15 | # ``` 16 | flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled 17 | 18 | linkage = ENV['USE_FRAMEWORKS'] 19 | if linkage != nil 20 | Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green 21 | use_frameworks! :linkage => linkage.to_sym 22 | end 23 | 24 | target 'ReactNativeImageResizerExample' do 25 | config = use_native_modules! 26 | 27 | # Flags change depending on the env values. 28 | flags = get_default_flags() 29 | 30 | use_react_native!( 31 | :path => config[:reactNativePath], 32 | # Hermes is now enabled by default. Disable by setting this flag to false. 33 | # Upcoming versions of React Native may rely on get_default_flags(), but 34 | # we make it explicit here to aid in the React Native upgrade process. 35 | :hermes_enabled => flags[:hermes_enabled], 36 | :fabric_enabled => flags[:fabric_enabled], 37 | # Enables Flipper. 38 | # 39 | # Note that if you have use_frameworks! enabled, Flipper will not work and 40 | # you should disable the next line. 41 | :flipper_configuration => flipper_config, 42 | # An absolute path to your application root. 43 | :app_path => "#{Pod::Config.instance.installation_root}/.." 44 | ) 45 | 46 | target 'ReactNativeImageResizerExampleTests' do 47 | inherit! :complete 48 | # Pods for testing 49 | end 50 | 51 | post_install do |installer| 52 | react_native_post_install( 53 | installer, 54 | # Set `mac_catalyst_enabled` to `true` in order to apply patches 55 | # necessary for Mac Catalyst builds 56 | :mac_catalyst_enabled => false 57 | ) 58 | __apply_Xcode_12_5_M1_post_install_workaround(installer) 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /example/ios/Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - boost (1.76.0) 3 | - CocoaAsyncSocket (7.6.5) 4 | - DoubleConversion (1.1.6) 5 | - FBLazyVector (0.71.8) 6 | - FBReactNativeSpec (0.71.8): 7 | - RCT-Folly (= 2021.07.22.00) 8 | - RCTRequired (= 0.71.8) 9 | - RCTTypeSafety (= 0.71.8) 10 | - React-Core (= 0.71.8) 11 | - React-jsi (= 0.71.8) 12 | - ReactCommon/turbomodule/core (= 0.71.8) 13 | - Flipper (0.125.0): 14 | - Flipper-Folly (~> 2.6) 15 | - Flipper-RSocket (~> 1.4) 16 | - Flipper-Boost-iOSX (1.76.0.1.11) 17 | - Flipper-DoubleConversion (3.2.0.1) 18 | - Flipper-Fmt (7.1.7) 19 | - Flipper-Folly (2.6.10): 20 | - Flipper-Boost-iOSX 21 | - Flipper-DoubleConversion 22 | - Flipper-Fmt (= 7.1.7) 23 | - Flipper-Glog 24 | - libevent (~> 2.1.12) 25 | - OpenSSL-Universal (= 1.1.1100) 26 | - Flipper-Glog (0.5.0.5) 27 | - Flipper-PeerTalk (0.0.4) 28 | - Flipper-RSocket (1.4.3): 29 | - Flipper-Folly (~> 2.6) 30 | - FlipperKit (0.125.0): 31 | - FlipperKit/Core (= 0.125.0) 32 | - FlipperKit/Core (0.125.0): 33 | - Flipper (~> 0.125.0) 34 | - FlipperKit/CppBridge 35 | - FlipperKit/FBCxxFollyDynamicConvert 36 | - FlipperKit/FBDefines 37 | - FlipperKit/FKPortForwarding 38 | - SocketRocket (~> 0.6.0) 39 | - FlipperKit/CppBridge (0.125.0): 40 | - Flipper (~> 0.125.0) 41 | - FlipperKit/FBCxxFollyDynamicConvert (0.125.0): 42 | - Flipper-Folly (~> 2.6) 43 | - FlipperKit/FBDefines (0.125.0) 44 | - FlipperKit/FKPortForwarding (0.125.0): 45 | - CocoaAsyncSocket (~> 7.6) 46 | - Flipper-PeerTalk (~> 0.0.4) 47 | - FlipperKit/FlipperKitHighlightOverlay (0.125.0) 48 | - FlipperKit/FlipperKitLayoutHelpers (0.125.0): 49 | - FlipperKit/Core 50 | - FlipperKit/FlipperKitHighlightOverlay 51 | - FlipperKit/FlipperKitLayoutTextSearchable 52 | - FlipperKit/FlipperKitLayoutIOSDescriptors (0.125.0): 53 | - FlipperKit/Core 54 | - FlipperKit/FlipperKitHighlightOverlay 55 | - FlipperKit/FlipperKitLayoutHelpers 56 | - YogaKit (~> 1.18) 57 | - FlipperKit/FlipperKitLayoutPlugin (0.125.0): 58 | - FlipperKit/Core 59 | - FlipperKit/FlipperKitHighlightOverlay 60 | - FlipperKit/FlipperKitLayoutHelpers 61 | - FlipperKit/FlipperKitLayoutIOSDescriptors 62 | - FlipperKit/FlipperKitLayoutTextSearchable 63 | - YogaKit (~> 1.18) 64 | - FlipperKit/FlipperKitLayoutTextSearchable (0.125.0) 65 | - FlipperKit/FlipperKitNetworkPlugin (0.125.0): 66 | - FlipperKit/Core 67 | - FlipperKit/FlipperKitReactPlugin (0.125.0): 68 | - FlipperKit/Core 69 | - FlipperKit/FlipperKitUserDefaultsPlugin (0.125.0): 70 | - FlipperKit/Core 71 | - FlipperKit/SKIOSNetworkPlugin (0.125.0): 72 | - FlipperKit/Core 73 | - FlipperKit/FlipperKitNetworkPlugin 74 | - fmt (6.2.1) 75 | - glog (0.3.5) 76 | - hermes-engine (0.71.8): 77 | - hermes-engine/Pre-built (= 0.71.8) 78 | - hermes-engine/Pre-built (0.71.8) 79 | - libevent (2.1.12) 80 | - OpenSSL-Universal (1.1.1100) 81 | - RCT-Folly (2021.07.22.00): 82 | - boost 83 | - DoubleConversion 84 | - fmt (~> 6.2.1) 85 | - glog 86 | - RCT-Folly/Default (= 2021.07.22.00) 87 | - RCT-Folly/Default (2021.07.22.00): 88 | - boost 89 | - DoubleConversion 90 | - fmt (~> 6.2.1) 91 | - glog 92 | - RCT-Folly/Futures (2021.07.22.00): 93 | - boost 94 | - DoubleConversion 95 | - fmt (~> 6.2.1) 96 | - glog 97 | - libevent 98 | - RCTRequired (0.71.8) 99 | - RCTTypeSafety (0.71.8): 100 | - FBLazyVector (= 0.71.8) 101 | - RCTRequired (= 0.71.8) 102 | - React-Core (= 0.71.8) 103 | - React (0.71.8): 104 | - React-Core (= 0.71.8) 105 | - React-Core/DevSupport (= 0.71.8) 106 | - React-Core/RCTWebSocket (= 0.71.8) 107 | - React-RCTActionSheet (= 0.71.8) 108 | - React-RCTAnimation (= 0.71.8) 109 | - React-RCTBlob (= 0.71.8) 110 | - React-RCTImage (= 0.71.8) 111 | - React-RCTLinking (= 0.71.8) 112 | - React-RCTNetwork (= 0.71.8) 113 | - React-RCTSettings (= 0.71.8) 114 | - React-RCTText (= 0.71.8) 115 | - React-RCTVibration (= 0.71.8) 116 | - React-callinvoker (0.71.8) 117 | - React-Codegen (0.71.8): 118 | - FBReactNativeSpec 119 | - hermes-engine 120 | - RCT-Folly 121 | - RCTRequired 122 | - RCTTypeSafety 123 | - React-Core 124 | - React-jsi 125 | - React-jsiexecutor 126 | - ReactCommon/turbomodule/bridging 127 | - ReactCommon/turbomodule/core 128 | - React-Core (0.71.8): 129 | - glog 130 | - hermes-engine 131 | - RCT-Folly (= 2021.07.22.00) 132 | - React-Core/Default (= 0.71.8) 133 | - React-cxxreact (= 0.71.8) 134 | - React-hermes 135 | - React-jsi (= 0.71.8) 136 | - React-jsiexecutor (= 0.71.8) 137 | - React-perflogger (= 0.71.8) 138 | - Yoga 139 | - React-Core/CoreModulesHeaders (0.71.8): 140 | - glog 141 | - hermes-engine 142 | - RCT-Folly (= 2021.07.22.00) 143 | - React-Core/Default 144 | - React-cxxreact (= 0.71.8) 145 | - React-hermes 146 | - React-jsi (= 0.71.8) 147 | - React-jsiexecutor (= 0.71.8) 148 | - React-perflogger (= 0.71.8) 149 | - Yoga 150 | - React-Core/Default (0.71.8): 151 | - glog 152 | - hermes-engine 153 | - RCT-Folly (= 2021.07.22.00) 154 | - React-cxxreact (= 0.71.8) 155 | - React-hermes 156 | - React-jsi (= 0.71.8) 157 | - React-jsiexecutor (= 0.71.8) 158 | - React-perflogger (= 0.71.8) 159 | - Yoga 160 | - React-Core/DevSupport (0.71.8): 161 | - glog 162 | - hermes-engine 163 | - RCT-Folly (= 2021.07.22.00) 164 | - React-Core/Default (= 0.71.8) 165 | - React-Core/RCTWebSocket (= 0.71.8) 166 | - React-cxxreact (= 0.71.8) 167 | - React-hermes 168 | - React-jsi (= 0.71.8) 169 | - React-jsiexecutor (= 0.71.8) 170 | - React-jsinspector (= 0.71.8) 171 | - React-perflogger (= 0.71.8) 172 | - Yoga 173 | - React-Core/RCTActionSheetHeaders (0.71.8): 174 | - glog 175 | - hermes-engine 176 | - RCT-Folly (= 2021.07.22.00) 177 | - React-Core/Default 178 | - React-cxxreact (= 0.71.8) 179 | - React-hermes 180 | - React-jsi (= 0.71.8) 181 | - React-jsiexecutor (= 0.71.8) 182 | - React-perflogger (= 0.71.8) 183 | - Yoga 184 | - React-Core/RCTAnimationHeaders (0.71.8): 185 | - glog 186 | - hermes-engine 187 | - RCT-Folly (= 2021.07.22.00) 188 | - React-Core/Default 189 | - React-cxxreact (= 0.71.8) 190 | - React-hermes 191 | - React-jsi (= 0.71.8) 192 | - React-jsiexecutor (= 0.71.8) 193 | - React-perflogger (= 0.71.8) 194 | - Yoga 195 | - React-Core/RCTBlobHeaders (0.71.8): 196 | - glog 197 | - hermes-engine 198 | - RCT-Folly (= 2021.07.22.00) 199 | - React-Core/Default 200 | - React-cxxreact (= 0.71.8) 201 | - React-hermes 202 | - React-jsi (= 0.71.8) 203 | - React-jsiexecutor (= 0.71.8) 204 | - React-perflogger (= 0.71.8) 205 | - Yoga 206 | - React-Core/RCTImageHeaders (0.71.8): 207 | - glog 208 | - hermes-engine 209 | - RCT-Folly (= 2021.07.22.00) 210 | - React-Core/Default 211 | - React-cxxreact (= 0.71.8) 212 | - React-hermes 213 | - React-jsi (= 0.71.8) 214 | - React-jsiexecutor (= 0.71.8) 215 | - React-perflogger (= 0.71.8) 216 | - Yoga 217 | - React-Core/RCTLinkingHeaders (0.71.8): 218 | - glog 219 | - hermes-engine 220 | - RCT-Folly (= 2021.07.22.00) 221 | - React-Core/Default 222 | - React-cxxreact (= 0.71.8) 223 | - React-hermes 224 | - React-jsi (= 0.71.8) 225 | - React-jsiexecutor (= 0.71.8) 226 | - React-perflogger (= 0.71.8) 227 | - Yoga 228 | - React-Core/RCTNetworkHeaders (0.71.8): 229 | - glog 230 | - hermes-engine 231 | - RCT-Folly (= 2021.07.22.00) 232 | - React-Core/Default 233 | - React-cxxreact (= 0.71.8) 234 | - React-hermes 235 | - React-jsi (= 0.71.8) 236 | - React-jsiexecutor (= 0.71.8) 237 | - React-perflogger (= 0.71.8) 238 | - Yoga 239 | - React-Core/RCTSettingsHeaders (0.71.8): 240 | - glog 241 | - hermes-engine 242 | - RCT-Folly (= 2021.07.22.00) 243 | - React-Core/Default 244 | - React-cxxreact (= 0.71.8) 245 | - React-hermes 246 | - React-jsi (= 0.71.8) 247 | - React-jsiexecutor (= 0.71.8) 248 | - React-perflogger (= 0.71.8) 249 | - Yoga 250 | - React-Core/RCTTextHeaders (0.71.8): 251 | - glog 252 | - hermes-engine 253 | - RCT-Folly (= 2021.07.22.00) 254 | - React-Core/Default 255 | - React-cxxreact (= 0.71.8) 256 | - React-hermes 257 | - React-jsi (= 0.71.8) 258 | - React-jsiexecutor (= 0.71.8) 259 | - React-perflogger (= 0.71.8) 260 | - Yoga 261 | - React-Core/RCTVibrationHeaders (0.71.8): 262 | - glog 263 | - hermes-engine 264 | - RCT-Folly (= 2021.07.22.00) 265 | - React-Core/Default 266 | - React-cxxreact (= 0.71.8) 267 | - React-hermes 268 | - React-jsi (= 0.71.8) 269 | - React-jsiexecutor (= 0.71.8) 270 | - React-perflogger (= 0.71.8) 271 | - Yoga 272 | - React-Core/RCTWebSocket (0.71.8): 273 | - glog 274 | - hermes-engine 275 | - RCT-Folly (= 2021.07.22.00) 276 | - React-Core/Default (= 0.71.8) 277 | - React-cxxreact (= 0.71.8) 278 | - React-hermes 279 | - React-jsi (= 0.71.8) 280 | - React-jsiexecutor (= 0.71.8) 281 | - React-perflogger (= 0.71.8) 282 | - Yoga 283 | - React-CoreModules (0.71.8): 284 | - RCT-Folly (= 2021.07.22.00) 285 | - RCTTypeSafety (= 0.71.8) 286 | - React-Codegen (= 0.71.8) 287 | - React-Core/CoreModulesHeaders (= 0.71.8) 288 | - React-jsi (= 0.71.8) 289 | - React-RCTBlob 290 | - React-RCTImage (= 0.71.8) 291 | - ReactCommon/turbomodule/core (= 0.71.8) 292 | - React-cxxreact (0.71.8): 293 | - boost (= 1.76.0) 294 | - DoubleConversion 295 | - glog 296 | - hermes-engine 297 | - RCT-Folly (= 2021.07.22.00) 298 | - React-callinvoker (= 0.71.8) 299 | - React-jsi (= 0.71.8) 300 | - React-jsinspector (= 0.71.8) 301 | - React-logger (= 0.71.8) 302 | - React-perflogger (= 0.71.8) 303 | - React-runtimeexecutor (= 0.71.8) 304 | - React-hermes (0.71.8): 305 | - DoubleConversion 306 | - glog 307 | - hermes-engine 308 | - RCT-Folly (= 2021.07.22.00) 309 | - RCT-Folly/Futures (= 2021.07.22.00) 310 | - React-cxxreact (= 0.71.8) 311 | - React-jsi 312 | - React-jsiexecutor (= 0.71.8) 313 | - React-jsinspector (= 0.71.8) 314 | - React-perflogger (= 0.71.8) 315 | - React-jsi (0.71.8): 316 | - boost (= 1.76.0) 317 | - DoubleConversion 318 | - glog 319 | - hermes-engine 320 | - RCT-Folly (= 2021.07.22.00) 321 | - React-jsiexecutor (0.71.8): 322 | - DoubleConversion 323 | - glog 324 | - hermes-engine 325 | - RCT-Folly (= 2021.07.22.00) 326 | - React-cxxreact (= 0.71.8) 327 | - React-jsi (= 0.71.8) 328 | - React-perflogger (= 0.71.8) 329 | - React-jsinspector (0.71.8) 330 | - React-logger (0.71.8): 331 | - glog 332 | - react-native-cameraroll (5.7.2): 333 | - React-Core 334 | - react-native-image-picker (4.10.3): 335 | - React-Core 336 | - react-native-image-resizer (3.0.5): 337 | - React-Core 338 | - React-perflogger (0.71.8) 339 | - React-RCTActionSheet (0.71.8): 340 | - React-Core/RCTActionSheetHeaders (= 0.71.8) 341 | - React-RCTAnimation (0.71.8): 342 | - RCT-Folly (= 2021.07.22.00) 343 | - RCTTypeSafety (= 0.71.8) 344 | - React-Codegen (= 0.71.8) 345 | - React-Core/RCTAnimationHeaders (= 0.71.8) 346 | - React-jsi (= 0.71.8) 347 | - ReactCommon/turbomodule/core (= 0.71.8) 348 | - React-RCTAppDelegate (0.71.8): 349 | - RCT-Folly 350 | - RCTRequired 351 | - RCTTypeSafety 352 | - React-Core 353 | - ReactCommon/turbomodule/core 354 | - React-RCTBlob (0.71.8): 355 | - hermes-engine 356 | - RCT-Folly (= 2021.07.22.00) 357 | - React-Codegen (= 0.71.8) 358 | - React-Core/RCTBlobHeaders (= 0.71.8) 359 | - React-Core/RCTWebSocket (= 0.71.8) 360 | - React-jsi (= 0.71.8) 361 | - React-RCTNetwork (= 0.71.8) 362 | - ReactCommon/turbomodule/core (= 0.71.8) 363 | - React-RCTImage (0.71.8): 364 | - RCT-Folly (= 2021.07.22.00) 365 | - RCTTypeSafety (= 0.71.8) 366 | - React-Codegen (= 0.71.8) 367 | - React-Core/RCTImageHeaders (= 0.71.8) 368 | - React-jsi (= 0.71.8) 369 | - React-RCTNetwork (= 0.71.8) 370 | - ReactCommon/turbomodule/core (= 0.71.8) 371 | - React-RCTLinking (0.71.8): 372 | - React-Codegen (= 0.71.8) 373 | - React-Core/RCTLinkingHeaders (= 0.71.8) 374 | - React-jsi (= 0.71.8) 375 | - ReactCommon/turbomodule/core (= 0.71.8) 376 | - React-RCTNetwork (0.71.8): 377 | - RCT-Folly (= 2021.07.22.00) 378 | - RCTTypeSafety (= 0.71.8) 379 | - React-Codegen (= 0.71.8) 380 | - React-Core/RCTNetworkHeaders (= 0.71.8) 381 | - React-jsi (= 0.71.8) 382 | - ReactCommon/turbomodule/core (= 0.71.8) 383 | - React-RCTSettings (0.71.8): 384 | - RCT-Folly (= 2021.07.22.00) 385 | - RCTTypeSafety (= 0.71.8) 386 | - React-Codegen (= 0.71.8) 387 | - React-Core/RCTSettingsHeaders (= 0.71.8) 388 | - React-jsi (= 0.71.8) 389 | - ReactCommon/turbomodule/core (= 0.71.8) 390 | - React-RCTText (0.71.8): 391 | - React-Core/RCTTextHeaders (= 0.71.8) 392 | - React-RCTVibration (0.71.8): 393 | - RCT-Folly (= 2021.07.22.00) 394 | - React-Codegen (= 0.71.8) 395 | - React-Core/RCTVibrationHeaders (= 0.71.8) 396 | - React-jsi (= 0.71.8) 397 | - ReactCommon/turbomodule/core (= 0.71.8) 398 | - React-runtimeexecutor (0.71.8): 399 | - React-jsi (= 0.71.8) 400 | - ReactCommon/turbomodule/bridging (0.71.8): 401 | - DoubleConversion 402 | - glog 403 | - hermes-engine 404 | - RCT-Folly (= 2021.07.22.00) 405 | - React-callinvoker (= 0.71.8) 406 | - React-Core (= 0.71.8) 407 | - React-cxxreact (= 0.71.8) 408 | - React-jsi (= 0.71.8) 409 | - React-logger (= 0.71.8) 410 | - React-perflogger (= 0.71.8) 411 | - ReactCommon/turbomodule/core (0.71.8): 412 | - DoubleConversion 413 | - glog 414 | - hermes-engine 415 | - RCT-Folly (= 2021.07.22.00) 416 | - React-callinvoker (= 0.71.8) 417 | - React-Core (= 0.71.8) 418 | - React-cxxreact (= 0.71.8) 419 | - React-jsi (= 0.71.8) 420 | - React-logger (= 0.71.8) 421 | - React-perflogger (= 0.71.8) 422 | - SocketRocket (0.6.0) 423 | - VisionCamera (2.15.6): 424 | - React 425 | - React-callinvoker 426 | - React-Core 427 | - Yoga (1.14.0) 428 | - YogaKit (1.18.1): 429 | - Yoga (~> 1.14) 430 | 431 | DEPENDENCIES: 432 | - boost (from `../node_modules/react-native/third-party-podspecs/boost.podspec`) 433 | - DoubleConversion (from `../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec`) 434 | - FBLazyVector (from `../node_modules/react-native/Libraries/FBLazyVector`) 435 | - FBReactNativeSpec (from `../node_modules/react-native/React/FBReactNativeSpec`) 436 | - Flipper (= 0.125.0) 437 | - Flipper-Boost-iOSX (= 1.76.0.1.11) 438 | - Flipper-DoubleConversion (= 3.2.0.1) 439 | - Flipper-Fmt (= 7.1.7) 440 | - Flipper-Folly (= 2.6.10) 441 | - Flipper-Glog (= 0.5.0.5) 442 | - Flipper-PeerTalk (= 0.0.4) 443 | - Flipper-RSocket (= 1.4.3) 444 | - FlipperKit (= 0.125.0) 445 | - FlipperKit/Core (= 0.125.0) 446 | - FlipperKit/CppBridge (= 0.125.0) 447 | - FlipperKit/FBCxxFollyDynamicConvert (= 0.125.0) 448 | - FlipperKit/FBDefines (= 0.125.0) 449 | - FlipperKit/FKPortForwarding (= 0.125.0) 450 | - FlipperKit/FlipperKitHighlightOverlay (= 0.125.0) 451 | - FlipperKit/FlipperKitLayoutPlugin (= 0.125.0) 452 | - FlipperKit/FlipperKitLayoutTextSearchable (= 0.125.0) 453 | - FlipperKit/FlipperKitNetworkPlugin (= 0.125.0) 454 | - FlipperKit/FlipperKitReactPlugin (= 0.125.0) 455 | - FlipperKit/FlipperKitUserDefaultsPlugin (= 0.125.0) 456 | - FlipperKit/SKIOSNetworkPlugin (= 0.125.0) 457 | - glog (from `../node_modules/react-native/third-party-podspecs/glog.podspec`) 458 | - hermes-engine (from `../node_modules/react-native/sdks/hermes-engine/hermes-engine.podspec`) 459 | - libevent (~> 2.1.12) 460 | - OpenSSL-Universal (= 1.1.1100) 461 | - RCT-Folly (from `../node_modules/react-native/third-party-podspecs/RCT-Folly.podspec`) 462 | - RCTRequired (from `../node_modules/react-native/Libraries/RCTRequired`) 463 | - RCTTypeSafety (from `../node_modules/react-native/Libraries/TypeSafety`) 464 | - React (from `../node_modules/react-native/`) 465 | - React-callinvoker (from `../node_modules/react-native/ReactCommon/callinvoker`) 466 | - React-Codegen (from `build/generated/ios`) 467 | - React-Core (from `../node_modules/react-native/`) 468 | - React-Core/DevSupport (from `../node_modules/react-native/`) 469 | - React-Core/RCTWebSocket (from `../node_modules/react-native/`) 470 | - React-CoreModules (from `../node_modules/react-native/React/CoreModules`) 471 | - React-cxxreact (from `../node_modules/react-native/ReactCommon/cxxreact`) 472 | - React-hermes (from `../node_modules/react-native/ReactCommon/hermes`) 473 | - React-jsi (from `../node_modules/react-native/ReactCommon/jsi`) 474 | - React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`) 475 | - React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`) 476 | - React-logger (from `../node_modules/react-native/ReactCommon/logger`) 477 | - "react-native-cameraroll (from `../node_modules/@react-native-camera-roll/camera-roll`)" 478 | - react-native-image-picker (from `../node_modules/react-native-image-picker`) 479 | - react-native-image-resizer (from `../..`) 480 | - React-perflogger (from `../node_modules/react-native/ReactCommon/reactperflogger`) 481 | - React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`) 482 | - React-RCTAnimation (from `../node_modules/react-native/Libraries/NativeAnimation`) 483 | - React-RCTAppDelegate (from `../node_modules/react-native/Libraries/AppDelegate`) 484 | - React-RCTBlob (from `../node_modules/react-native/Libraries/Blob`) 485 | - React-RCTImage (from `../node_modules/react-native/Libraries/Image`) 486 | - React-RCTLinking (from `../node_modules/react-native/Libraries/LinkingIOS`) 487 | - React-RCTNetwork (from `../node_modules/react-native/Libraries/Network`) 488 | - React-RCTSettings (from `../node_modules/react-native/Libraries/Settings`) 489 | - React-RCTText (from `../node_modules/react-native/Libraries/Text`) 490 | - React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`) 491 | - React-runtimeexecutor (from `../node_modules/react-native/ReactCommon/runtimeexecutor`) 492 | - ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`) 493 | - VisionCamera (from `../node_modules/react-native-vision-camera`) 494 | - Yoga (from `../node_modules/react-native/ReactCommon/yoga`) 495 | 496 | SPEC REPOS: 497 | trunk: 498 | - CocoaAsyncSocket 499 | - Flipper 500 | - Flipper-Boost-iOSX 501 | - Flipper-DoubleConversion 502 | - Flipper-Fmt 503 | - Flipper-Folly 504 | - Flipper-Glog 505 | - Flipper-PeerTalk 506 | - Flipper-RSocket 507 | - FlipperKit 508 | - fmt 509 | - libevent 510 | - OpenSSL-Universal 511 | - SocketRocket 512 | - YogaKit 513 | 514 | EXTERNAL SOURCES: 515 | boost: 516 | :podspec: "../node_modules/react-native/third-party-podspecs/boost.podspec" 517 | DoubleConversion: 518 | :podspec: "../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec" 519 | FBLazyVector: 520 | :path: "../node_modules/react-native/Libraries/FBLazyVector" 521 | FBReactNativeSpec: 522 | :path: "../node_modules/react-native/React/FBReactNativeSpec" 523 | glog: 524 | :podspec: "../node_modules/react-native/third-party-podspecs/glog.podspec" 525 | hermes-engine: 526 | :podspec: "../node_modules/react-native/sdks/hermes-engine/hermes-engine.podspec" 527 | RCT-Folly: 528 | :podspec: "../node_modules/react-native/third-party-podspecs/RCT-Folly.podspec" 529 | RCTRequired: 530 | :path: "../node_modules/react-native/Libraries/RCTRequired" 531 | RCTTypeSafety: 532 | :path: "../node_modules/react-native/Libraries/TypeSafety" 533 | React: 534 | :path: "../node_modules/react-native/" 535 | React-callinvoker: 536 | :path: "../node_modules/react-native/ReactCommon/callinvoker" 537 | React-Codegen: 538 | :path: build/generated/ios 539 | React-Core: 540 | :path: "../node_modules/react-native/" 541 | React-CoreModules: 542 | :path: "../node_modules/react-native/React/CoreModules" 543 | React-cxxreact: 544 | :path: "../node_modules/react-native/ReactCommon/cxxreact" 545 | React-hermes: 546 | :path: "../node_modules/react-native/ReactCommon/hermes" 547 | React-jsi: 548 | :path: "../node_modules/react-native/ReactCommon/jsi" 549 | React-jsiexecutor: 550 | :path: "../node_modules/react-native/ReactCommon/jsiexecutor" 551 | React-jsinspector: 552 | :path: "../node_modules/react-native/ReactCommon/jsinspector" 553 | React-logger: 554 | :path: "../node_modules/react-native/ReactCommon/logger" 555 | react-native-cameraroll: 556 | :path: "../node_modules/@react-native-camera-roll/camera-roll" 557 | react-native-image-picker: 558 | :path: "../node_modules/react-native-image-picker" 559 | react-native-image-resizer: 560 | :path: "../.." 561 | React-perflogger: 562 | :path: "../node_modules/react-native/ReactCommon/reactperflogger" 563 | React-RCTActionSheet: 564 | :path: "../node_modules/react-native/Libraries/ActionSheetIOS" 565 | React-RCTAnimation: 566 | :path: "../node_modules/react-native/Libraries/NativeAnimation" 567 | React-RCTAppDelegate: 568 | :path: "../node_modules/react-native/Libraries/AppDelegate" 569 | React-RCTBlob: 570 | :path: "../node_modules/react-native/Libraries/Blob" 571 | React-RCTImage: 572 | :path: "../node_modules/react-native/Libraries/Image" 573 | React-RCTLinking: 574 | :path: "../node_modules/react-native/Libraries/LinkingIOS" 575 | React-RCTNetwork: 576 | :path: "../node_modules/react-native/Libraries/Network" 577 | React-RCTSettings: 578 | :path: "../node_modules/react-native/Libraries/Settings" 579 | React-RCTText: 580 | :path: "../node_modules/react-native/Libraries/Text" 581 | React-RCTVibration: 582 | :path: "../node_modules/react-native/Libraries/Vibration" 583 | React-runtimeexecutor: 584 | :path: "../node_modules/react-native/ReactCommon/runtimeexecutor" 585 | ReactCommon: 586 | :path: "../node_modules/react-native/ReactCommon" 587 | VisionCamera: 588 | :path: "../node_modules/react-native-vision-camera" 589 | Yoga: 590 | :path: "../node_modules/react-native/ReactCommon/yoga" 591 | 592 | SPEC CHECKSUMS: 593 | boost: a7c83b31436843459a1961bfd74b96033dc77234 594 | CocoaAsyncSocket: 065fd1e645c7abab64f7a6a2007a48038fdc6a99 595 | DoubleConversion: 831926d9b8bf8166fd87886c4abab286c2422662 596 | FBLazyVector: f637f31eacba90d4fdeff3fa41608b8f361c173b 597 | FBReactNativeSpec: 0d9a4f4de7ab614c49e98c00aedfd3bfbda33d59 598 | Flipper: 26fc4b7382499f1281eb8cb921e5c3ad6de91fe0 599 | Flipper-Boost-iOSX: fd1e2b8cbef7e662a122412d7ac5f5bea715403c 600 | Flipper-DoubleConversion: 2dc99b02f658daf147069aad9dbd29d8feb06d30 601 | Flipper-Fmt: 60cbdd92fc254826e61d669a5d87ef7015396a9b 602 | Flipper-Folly: 584845625005ff068a6ebf41f857f468decd26b3 603 | Flipper-Glog: 70c50ce58ddaf67dc35180db05f191692570f446 604 | Flipper-PeerTalk: 116d8f857dc6ef55c7a5a75ea3ceaafe878aadc9 605 | Flipper-RSocket: d9d9ade67cbecf6ac10730304bf5607266dd2541 606 | FlipperKit: cbdee19bdd4e7f05472a66ce290f1b729ba3cb86 607 | fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9 608 | glog: 476ee3e89abb49e07f822b48323c51c57124b572 609 | hermes-engine: 47986d26692ae75ee7a17ab049caee8864f855de 610 | libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913 611 | OpenSSL-Universal: ebc357f1e6bc71fa463ccb2fe676756aff50e88c 612 | RCT-Folly: 424b8c9a7a0b9ab2886ffe9c3b041ef628fd4fb1 613 | RCTRequired: 8af6a32dfc2b65ec82193c2dee6e1011ff22ac2a 614 | RCTTypeSafety: bee9dd161c175896c680d47ef1d9eaacf2b587f4 615 | React: d850475db9ba8006a8b875d79e1e0d6ac8a0f8b6 616 | React-callinvoker: 6a0c75475ddc17c9ed54e4ff0478074a18fd7ab5 617 | React-Codegen: 786571642e87add634e7f4d299c85314ec6cc158 618 | React-Core: 1adfab153f59e4f56e09b97a153089f466d7b8aa 619 | React-CoreModules: 958d236715415d4ccdd5fa35c516cf0356637393 620 | React-cxxreact: 2e7a6283807ce8755c3d501735acd400bec3b5cd 621 | React-hermes: 8102c3112ba32207c3052619be8cfae14bf99d84 622 | React-jsi: dd29264f041a587e91f994e4be97e86c127742b2 623 | React-jsiexecutor: 747911ab5921641b4ed7e4900065896597142125 624 | React-jsinspector: c712f9e3bb9ba4122d6b82b4f906448b8a281580 625 | React-logger: 342f358b8decfbf8f272367f4eacf4b6154061be 626 | react-native-cameraroll: 134805127580aed23403b8c2cb1548920dd77b3a 627 | react-native-image-picker: 60f4246eb5bb7187fc15638a8c1f13abd3820695 628 | react-native-image-resizer: 00ceb0e05586c7aadf061eea676957a6c2ec60fa 629 | React-perflogger: d21f182895de9d1b077f8a3cd00011095c8c9100 630 | React-RCTActionSheet: 0151f83ef92d2a7139bba7dfdbc8066632a6d47b 631 | React-RCTAnimation: 5ec9c0705bb2297549c120fe6473aa3e4a01e215 632 | React-RCTAppDelegate: 9895fd1b6d1176d88c4b10ddc169b2e1300c91f0 633 | React-RCTBlob: f3634eb45b6e7480037655e1ca93d1136ac984dd 634 | React-RCTImage: 3c12cb32dec49549ae62ed6cba4018db43841ffc 635 | React-RCTLinking: 310e930ee335ef25481b4a173d9edb64b77895f9 636 | React-RCTNetwork: b6837841fe88303b0c04c1e3c01992b30f1f5498 637 | React-RCTSettings: 600d91fe25fa7c16b0ff891304082440f2904b89 638 | React-RCTText: a0a19f749088280c6def5397ed6211b811e7eef3 639 | React-RCTVibration: 43ffd976a25f6057a7cf95ea3648ba4e00287f89 640 | React-runtimeexecutor: 7c51ae9d4b3e9608a2366e39ccaa606aa551b9ed 641 | ReactCommon: 85c98ab0a509e70bf5ee5d9715cf68dbf495b84c 642 | SocketRocket: fccef3f9c5cedea1353a9ef6ada904fde10d6608 643 | VisionCamera: 523b49054bee9dace64189ab6631cb41e8b83fe0 644 | Yoga: 065f0b74dba4832d6e328238de46eb72c5de9556 645 | YogaKit: f782866e155069a2cca2517aafea43200b01fd5a 646 | 647 | PODFILE CHECKSUM: d12e6625eb5869c057639e02d65105cb9b470445 648 | 649 | COCOAPODS: 1.12.1 650 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | // 2 | // Use this file to import your target's public headers that you would like to expose to Swift. 3 | // 4 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample.xcodeproj/xcshareddata/xcschemes/ReactNativeImageResizerExample.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : RCTAppDelegate 5 | 6 | @end 7 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample/AppDelegate.mm: -------------------------------------------------------------------------------- 1 | #import "AppDelegate.h" 2 | 3 | #import 4 | 5 | @implementation AppDelegate 6 | 7 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 8 | { 9 | self.moduleName = @"ReactNativeImageResizerExample"; 10 | // You can add your custom initial props in the dictionary below. 11 | // They will be passed down to the ViewController used by React Native. 12 | self.initialProps = @{}; 13 | 14 | return [super application:application didFinishLaunchingWithOptions:launchOptions]; 15 | } 16 | 17 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 18 | { 19 | #if DEBUG 20 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; 21 | #else 22 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 23 | #endif 24 | } 25 | 26 | /// This method controls whether the `concurrentRoot`feature of React18 is turned on or off. 27 | /// 28 | /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html 29 | /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture). 30 | /// @return: `true` if the `concurrentRoot` feature is enabled. Otherwise, it returns `false`. 31 | - (BOOL)concurrentRootEnabled 32 | { 33 | return true; 34 | } 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ios-marketing", 45 | "scale" : "1x", 46 | "size" : "1024x1024" 47 | } 48 | ], 49 | "info" : { 50 | "author" : "xcode", 51 | "version" : 1 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | ReactNativeImageResizerExample 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(MARKETING_VERSION) 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | $(CURRENT_PROJECT_VERSION) 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSExceptionDomains 30 | 31 | localhost 32 | 33 | NSExceptionAllowsInsecureHTTPLoads 34 | 35 | 36 | 37 | 38 | NSLocationWhenInUseUsageDescription 39 | 40 | UILaunchStoryboardName 41 | LaunchScreen 42 | UIRequiredDeviceCapabilities 43 | 44 | armv7 45 | 46 | UISupportedInterfaceOrientations 47 | 48 | UIInterfaceOrientationPortrait 49 | UIInterfaceOrientationLandscapeLeft 50 | UIInterfaceOrientationLandscapeRight 51 | 52 | UIViewControllerBasedStatusBarAppearance 53 | 54 | NSCameraUsageDescription 55 | $(PRODUCT_NAME) needs access to your Camera. 56 | NSPhotoLibraryUsageDescription 57 | $(PRODUCT_NAME) needs access your photo library. 58 | NSPhotoLibraryAddUsageDescription 59 | $(PRODUCT_NAME) needs access your photo library. 60 | 61 | 62 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 24 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExample/main.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "AppDelegate.h" 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | @autoreleasepool { 8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExampleTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/ios/ReactNativeImageResizerExampleTests/ReactNativeImageResizerExampleTests.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import 5 | #import 6 | 7 | #define TIMEOUT_SECONDS 600 8 | #define TEXT_TO_LOOK_FOR @"Welcome to React" 9 | 10 | @interface ReactNativeImageResizerExampleTests : XCTestCase 11 | 12 | @end 13 | 14 | @implementation ReactNativeImageResizerExampleTests 15 | 16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test 17 | { 18 | if (test(view)) { 19 | return YES; 20 | } 21 | for (UIView *subview in [view subviews]) { 22 | if ([self findSubviewInView:subview matching:test]) { 23 | return YES; 24 | } 25 | } 26 | return NO; 27 | } 28 | 29 | - (void)testRendersWelcomeScreen 30 | { 31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 33 | BOOL foundElement = NO; 34 | 35 | __block NSString *redboxError = nil; 36 | #ifdef DEBUG 37 | RCTSetLogFunction( 38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 39 | if (level >= RCTLogLevelError) { 40 | redboxError = message; 41 | } 42 | }); 43 | #endif 44 | 45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 48 | 49 | foundElement = [self findSubviewInView:vc.view 50 | matching:^BOOL(UIView *view) { 51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 52 | return YES; 53 | } 54 | return NO; 55 | }]; 56 | } 57 | 58 | #ifdef DEBUG 59 | RCTSetLogFunction(RCTDefaultLogFunction); 60 | #endif 61 | 62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const escape = require('escape-string-regexp'); 3 | const exclusionList = require('metro-config/src/defaults/exclusionList'); 4 | const pak = require('../package.json'); 5 | 6 | const root = path.resolve(__dirname, '..'); 7 | 8 | const modules = Object.keys({ 9 | ...pak.peerDependencies, 10 | }); 11 | 12 | module.exports = { 13 | projectRoot: __dirname, 14 | watchFolders: [root], 15 | 16 | // We need to make sure that only one version is loaded for peerDependencies 17 | // So we block them at the root, and alias them to the versions in example's node_modules 18 | resolver: { 19 | blacklistRE: exclusionList( 20 | modules.map( 21 | (m) => 22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 23 | ) 24 | ), 25 | 26 | extraNodeModules: modules.reduce((acc, name) => { 27 | acc[name] = path.join(__dirname, 'node_modules', name); 28 | return acc; 29 | }, {}), 30 | }, 31 | 32 | transformer: { 33 | getTransformOptions: async () => ({ 34 | transform: { 35 | experimentalImportSupport: false, 36 | inlineRequires: true, 37 | }, 38 | }), 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ReactNativeImageResizerExample", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "android": "react-native run-android", 7 | "ios": "react-native run-ios", 8 | "start": "react-native start", 9 | "pods": "pod-install --quiet" 10 | }, 11 | "dependencies": { 12 | "@react-native-camera-roll/camera-roll": "^5.7.2", 13 | "react": "18.2.0", 14 | "react-native": "0.71.8", 15 | "react-native-image-picker": "^4.8.4", 16 | "react-native-vision-camera": "^2.15.6" 17 | }, 18 | "devDependencies": { 19 | "@babel/core": "^7.20.0", 20 | "@babel/preset-env": "^7.20.0", 21 | "@babel/runtime": "^7.20.0", 22 | "babel-plugin-module-resolver": "^4.1.0", 23 | "metro-react-native-babel-preset": "0.73.9" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /example/react-native.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = { 5 | dependencies: { 6 | [pak.name]: { 7 | root: path.join(__dirname, '..'), 8 | }, 9 | }, 10 | }; 11 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * Sample React Native App 3 | * https://github.com/facebook/react-native 4 | * 5 | * Generated with the TypeScript template 6 | * https://github.com/react-native-community/react-native-template-typescript 7 | * 8 | * @format 9 | */ 10 | 11 | import React, { useRef, useState } from 'react'; 12 | import { 13 | Alert, 14 | Image, 15 | PermissionsAndroid, 16 | Platform, 17 | ScrollView, 18 | StyleSheet, 19 | Text, 20 | TextInput, 21 | TouchableOpacity, 22 | View, 23 | } from 'react-native'; 24 | import ImageResizer from '@bam.tech/react-native-image-resizer'; 25 | import type { 26 | ResizeMode, 27 | Response, 28 | } from '@bam.tech/react-native-image-resizer'; 29 | import { launchImageLibrary } from 'react-native-image-picker'; 30 | import { Camera, useCameraDevices } from 'react-native-vision-camera'; 31 | import { CameraRoll } from '@react-native-camera-roll/camera-roll'; 32 | 33 | const modeOptions: { label: string; value: ResizeMode }[] = [ 34 | { 35 | label: 'contain', 36 | value: 'contain', 37 | }, 38 | { 39 | label: 'cover', 40 | value: 'cover', 41 | }, 42 | { 43 | label: 'stretch', 44 | value: 'stretch', 45 | }, 46 | ]; 47 | 48 | const onlyScaleDownOptions: { label: string; value: boolean }[] = [ 49 | { 50 | label: 'true', 51 | value: true, 52 | }, 53 | { 54 | label: 'false', 55 | value: false, 56 | }, 57 | ]; 58 | 59 | async function hasCameraRollPermissions() { 60 | const getCheckPermissionPromise = () => { 61 | if (Platform.OS === 'ios') { 62 | return true; 63 | } 64 | 65 | if (Number(Platform.Version) >= 33) { 66 | return Promise.all([ 67 | PermissionsAndroid.check('android.permission.READ_MEDIA_IMAGES'), 68 | ]).then(([hasReadMediaImagesPermission]) => hasReadMediaImagesPermission); 69 | } else { 70 | return PermissionsAndroid.check( 71 | 'android.permission.READ_EXTERNAL_STORAGE' 72 | ); 73 | } 74 | }; 75 | 76 | const hasPermission = await getCheckPermissionPromise(); 77 | if (hasPermission) { 78 | return true; 79 | } 80 | const getRequestPermissionPromise = () => { 81 | if (Number(Platform.Version) >= 33) { 82 | return PermissionsAndroid.requestMultiple([ 83 | 'android.permission.READ_MEDIA_IMAGES', 84 | ]).then( 85 | (statuses) => 86 | statuses['android.permission.READ_MEDIA_IMAGES'] === 87 | PermissionsAndroid.RESULTS.GRANTED 88 | ); 89 | } else { 90 | return PermissionsAndroid.request( 91 | 'android.permission.READ_EXTERNAL_STORAGE' 92 | ).then((status) => status === PermissionsAndroid.RESULTS.GRANTED); 93 | } 94 | }; 95 | 96 | return await getRequestPermissionPromise(); 97 | } 98 | 99 | const App = () => { 100 | const [selectedMode, setMode] = useState('contain'); 101 | const [onlyScaleDown, setOnlyScaleDown] = useState(false); 102 | const [imageUri, setImageUri] = useState(); 103 | const [sizeTarget, setSizeTarget] = useState(80); 104 | const [resizedImage, setResizedImage] = useState(); 105 | const [isCameraActive, setIsCameraActive] = useState(false); 106 | const [inputImageUrl, setInputImageUrl] = useState(''); 107 | const devices = useCameraDevices(); 108 | const device = devices.back; 109 | const camera = useRef(null); 110 | 111 | const resize = async () => { 112 | if (!imageUri) return; 113 | 114 | setResizedImage(null); 115 | 116 | try { 117 | let result = await ImageResizer.createResizedImage( 118 | imageUri, 119 | sizeTarget, 120 | sizeTarget, 121 | 'JPEG', 122 | 100, 123 | 0, 124 | undefined, 125 | false, 126 | { 127 | mode: selectedMode, 128 | onlyScaleDown, 129 | } 130 | ); 131 | 132 | setResizedImage(result); 133 | } catch (error) { 134 | Alert.alert('Unable to resize the photo'); 135 | } 136 | }; 137 | 138 | const selectImageFromPicker = async () => { 139 | launchImageLibrary({ mediaType: 'photo' }, (response) => { 140 | if (!response || !response.assets) return; 141 | const asset = response.assets[0]; 142 | if (asset) { 143 | setImageUri(asset.uri); 144 | } 145 | }); 146 | }; 147 | 148 | const selectFirstImageFromCameraRoll = async () => { 149 | const hasPermission = await hasCameraRollPermissions(); 150 | if (!hasPermission) { 151 | Alert.prompt('No permission to access photo library'); 152 | return; 153 | } 154 | 155 | const result = await CameraRoll.getPhotos({ first: 1 }); 156 | if (result.edges.length === 0) { 157 | Alert.prompt('Can not load first image from camera roll'); 158 | } 159 | 160 | setImageUri(result.edges[0]?.node.image.uri); 161 | }; 162 | 163 | const hasCameraPermission = async () => { 164 | const cameraPermission = await Camera.getCameraPermissionStatus(); 165 | 166 | switch (cameraPermission) { 167 | case 'authorized': 168 | return true; 169 | case 'not-determined': 170 | case 'denied': 171 | const newCameraPermission = await Camera.requestCameraPermission(); 172 | return newCameraPermission === 'authorized'; 173 | default: 174 | Alert.alert('Go in app settings to allow camera usage'); 175 | return false; 176 | } 177 | }; 178 | 179 | const openCamera = async () => { 180 | setIsCameraActive(await hasCameraPermission()); 181 | }; 182 | 183 | const takePhoto = async () => { 184 | if (camera.current === null) { 185 | return; 186 | } 187 | 188 | const photo = await camera.current.takePhoto(); 189 | // Adding file:// is mandatory in Android in order to display the image properly with 190 | setImageUri((Platform.OS === 'android' ? 'file://' : '') + photo.path); 191 | closeCamera(); 192 | }; 193 | 194 | const loadImageFromUrl = () => setImageUri(inputImageUrl); 195 | 196 | const closeCamera = () => setIsCameraActive(false); 197 | 198 | if (isCameraActive && device !== undefined) { 199 | return ( 200 | 201 | 209 | 210 | 211 | Capture 212 | 213 | 214 | 215 | 216 | Close 217 | 218 | 219 | 220 | ); 221 | } 222 | 223 | return ( 224 | 228 | Image Resizer example 229 | 230 | 231 | {'Select an image (react-native-image-picker)'} 232 | 233 | 234 | 235 | 239 | 240 | { 241 | 'Load first image of camera roll (@react-native-camera-roll/camera-roll)' 242 | } 243 | 244 | 245 | 246 | 247 | 248 | Take a photo 249 | 250 | 251 | setInputImageUrl(text)} 254 | placeholder="url" 255 | placeholderTextColor={'grey'} 256 | /> 257 | 258 | 259 | Load image from url 260 | 261 | 262 | This is the original image: 263 | {imageUri ? ( 264 | 269 | ) : null} 270 | 271 | Resized image: 272 | Mode: 273 | 274 | {modeOptions.map((mode) => ( 275 | setMode(mode.value)} 278 | key={mode.label} 279 | > 280 | {`${mode.label} ${ 281 | selectedMode === mode.value ? '✅' : '' 282 | }`} 283 | 284 | ))} 285 | 286 | 287 | Only scale down? 288 | 289 | {onlyScaleDownOptions.map((scaleDownOption) => ( 290 | setOnlyScaleDown(scaleDownOption.value)} 293 | key={scaleDownOption.label} 294 | > 295 | {`${scaleDownOption.label} ${ 296 | onlyScaleDown === scaleDownOption.value ? '✅' : '' 297 | }`} 298 | 299 | ))} 300 | 301 | 302 | Target size: 303 | { 308 | setSizeTarget(Number(text)); 309 | }} 310 | /> 311 | 312 | 313 | Click me to resize the image 314 | 315 | {resizedImage ? ( 316 | <> 317 | 322 | Width: {resizedImage.width} 323 | Height: {resizedImage.height} 324 | 325 | ) : null} 326 | 327 | ); 328 | }; 329 | 330 | const styles = StyleSheet.create({ 331 | scrollView: { 332 | backgroundColor: '#F5FCFF', 333 | }, 334 | container: { 335 | paddingVertical: 100, 336 | paddingHorizontal: 10, 337 | }, 338 | cameraContainer: { 339 | flex: 1, 340 | justifyContent: 'flex-end', 341 | }, 342 | imageSourceButtonContainer: { 343 | marginBottom: 10, 344 | }, 345 | welcome: { 346 | fontSize: 20, 347 | margin: 10, 348 | }, 349 | instructions: { 350 | textAlign: 'center', 351 | color: '#333333', 352 | marginBottom: 5, 353 | }, 354 | image: { 355 | height: 250, 356 | marginBottom: 10, 357 | }, 358 | resizeButton: { 359 | color: '#333333', 360 | fontWeight: 'bold', 361 | marginBottom: 5, 362 | }, 363 | button: { 364 | backgroundColor: '#2596be', 365 | paddingHorizontal: 30, 366 | paddingVertical: 20, 367 | borderRadius: 10, 368 | alignItems: 'center', 369 | }, 370 | optionContainer: { 371 | alignSelf: 'stretch', 372 | flexDirection: 'row', 373 | justifyContent: 'space-around', 374 | marginBottom: 10, 375 | }, 376 | cameraButtonContainer: { 377 | marginBottom: 40, 378 | marginHorizontal: 20, 379 | }, 380 | buttonOption: { 381 | backgroundColor: '#2596be', 382 | paddingHorizontal: 10, 383 | paddingVertical: 10, 384 | borderRadius: 10, 385 | }, 386 | textInput: { 387 | height: 40, 388 | borderColor: 'black', 389 | borderWidth: 2, 390 | margin: 10, 391 | alignSelf: 'stretch', 392 | textAlign: 'center', 393 | overflow: 'hidden', 394 | }, 395 | }); 396 | 397 | export default App; 398 | -------------------------------------------------------------------------------- /ios/ImageHelpers.h: -------------------------------------------------------------------------------- 1 | /* 2 | File: ImageHelpers.h 3 | 4 | Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple 5 | Inc. ("Apple") in consideration of your agreement to the following 6 | terms, and your use, installation, modification or redistribution of 7 | this Apple software constitutes acceptance of these terms. If you do 8 | not agree with these terms, please do not use, install, modify or 9 | redistribute this Apple software. 10 | 11 | In consideration of your agreement to abide by the following terms, and 12 | subject to these terms, Apple grants you a personal, non-exclusive 13 | license, under Apple's copyrights in this original Apple software (the 14 | "Apple Software"), to use, reproduce, modify and redistribute the Apple 15 | Software, with or without modifications, in source and/or binary forms; 16 | provided that if you redistribute the Apple Software in its entirety and 17 | without modifications, you must retain this notice and the following 18 | text and disclaimers in all such redistributions of the Apple Software. 19 | Neither the name, trademarks, service marks or logos of Apple Inc. may 20 | be used to endorse or promote products derived from the Apple Software 21 | without specific prior written permission from Apple. Except as 22 | expressly stated in this notice, no other rights or licenses, express or 23 | implied, are granted by Apple herein, including but not limited to any 24 | patent rights that may be infringed by your derivative works or by other 25 | works in which the Apple Software may be incorporated. 26 | 27 | The Apple Software is provided by Apple on an "AS IS" basis. APPLE 28 | MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION 29 | THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS 30 | FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND 31 | OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. 32 | 33 | IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL 34 | OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 35 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 36 | INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, 37 | MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED 38 | AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), 39 | STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE 40 | POSSIBILITY OF SUCH DAMAGE. 41 | 42 | Copyright (C) 2009 Apple Inc. All Rights Reserved. 43 | */ 44 | 45 | #include 46 | 47 | extern const CGBitmapInfo kDefaultCGBitmapInfo; 48 | extern const CGBitmapInfo kDefaultCGBitmapInfoNoAlpha; 49 | 50 | float GetScaleForProportionalResize( CGSize theSize, CGSize intoSize, bool onlyScaleDown, bool maximize ); 51 | CGContextRef CreateCGBitmapContextForWidthAndHeight( unsigned int width, unsigned int height, CGColorSpaceRef optionalColorSpace, CGBitmapInfo optionalInfo ); 52 | 53 | CGImageRef CreateCGImageFromUIImageScaled( UIImage* inImage, float scaleFactor ); 54 | 55 | @interface UIImage (scale) 56 | -(UIImage*)scaleToSize:(CGSize)toSize; 57 | @end 58 | -------------------------------------------------------------------------------- /ios/ImageHelpers.m: -------------------------------------------------------------------------------- 1 | /* 2 | File: ImageHelpers.m 3 | 4 | Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple 5 | Inc. ("Apple") in consideration of your agreement to the following 6 | terms, and your use, installation, modification or redistribution of 7 | this Apple software constitutes acceptance of these terms. If you do 8 | not agree with these terms, please do not use, install, modify or 9 | redistribute this Apple software. 10 | 11 | In consideration of your agreement to abide by the following terms, and 12 | subject to these terms, Apple grants you a personal, non-exclusive 13 | license, under Apple's copyrights in this original Apple software (the 14 | "Apple Software"), to use, reproduce, modify and redistribute the Apple 15 | Software, with or without modifications, in source and/or binary forms; 16 | provided that if you redistribute the Apple Software in its entirety and 17 | without modifications, you must retain this notice and the following 18 | text and disclaimers in all such redistributions of the Apple Software. 19 | Neither the name, trademarks, service marks or logos of Apple Inc. may 20 | be used to endorse or promote products derived from the Apple Software 21 | without specific prior written permission from Apple. Except as 22 | expressly stated in this notice, no other rights or licenses, express or 23 | implied, are granted by Apple herein, including but not limited to any 24 | patent rights that may be infringed by your derivative works or by other 25 | works in which the Apple Software may be incorporated. 26 | 27 | The Apple Software is provided by Apple on an "AS IS" basis. APPLE 28 | MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION 29 | THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS 30 | FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND 31 | OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. 32 | 33 | IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL 34 | OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 35 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 36 | INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, 37 | MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED 38 | AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), 39 | STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE 40 | POSSIBILITY OF SUCH DAMAGE. 41 | 42 | Copyright (C) 2009 Apple Inc. All Rights Reserved. 43 | */ 44 | 45 | #include "ImageHelpers.h" 46 | 47 | const CGBitmapInfo kDefaultCGBitmapInfo = (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host); 48 | const CGBitmapInfo kDefaultCGBitmapInfoNoAlpha = (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host); 49 | 50 | CGColorSpaceRef GetDeviceRGBColorSpace() { 51 | static CGColorSpaceRef deviceRGBSpace = NULL; 52 | if( deviceRGBSpace == NULL ) 53 | deviceRGBSpace = CGColorSpaceCreateDeviceRGB(); 54 | return deviceRGBSpace; 55 | } 56 | 57 | float GetScaleForProportionalResize( CGSize theSize, CGSize intoSize, bool onlyScaleDown, bool maximize ) 58 | { 59 | float sx = theSize.width; 60 | float sy = theSize.height; 61 | float dx = intoSize.width; 62 | float dy = intoSize.height; 63 | float scale = 1; 64 | 65 | if( sx != 0 && sy != 0 ) 66 | { 67 | dx = dx / sx; 68 | dy = dy / sy; 69 | 70 | // if maximize is true, take LARGER of the scales, else smaller 71 | if( maximize ) scale = (dx > dy) ? dx : dy; 72 | else scale = (dx < dy) ? dx : dy; 73 | 74 | if( scale > 1 && onlyScaleDown ) // reset scale 75 | scale = 1; 76 | } 77 | else 78 | { 79 | scale = 0; 80 | } 81 | return scale; 82 | } 83 | 84 | CGContextRef CreateCGBitmapContextForWidthAndHeight( unsigned int width, unsigned int height, 85 | CGColorSpaceRef optionalColorSpace, CGBitmapInfo optionalInfo ) 86 | { 87 | CGColorSpaceRef colorSpace = (optionalColorSpace == NULL) ? GetDeviceRGBColorSpace() : optionalColorSpace; 88 | CGBitmapInfo alphaInfo = ( (int32_t)optionalInfo < 0 ) ? kDefaultCGBitmapInfo : optionalInfo; 89 | return CGBitmapContextCreate( NULL, width, height, 8, 0, colorSpace, alphaInfo ); 90 | } 91 | 92 | CGImageRef CreateCGImageFromUIImageScaled( UIImage* image, float scaleFactor ) 93 | { 94 | CGImageRef newImage = NULL; 95 | CGContextRef bmContext = NULL; 96 | BOOL mustTransform = YES; 97 | CGAffineTransform transform = CGAffineTransformIdentity; 98 | UIImageOrientation orientation = image.imageOrientation; 99 | 100 | CGImageRef srcCGImage = CGImageRetain( image.CGImage ); 101 | 102 | size_t width = CGImageGetWidth(srcCGImage) * scaleFactor; 103 | size_t height = CGImageGetHeight(srcCGImage) * scaleFactor; 104 | 105 | // These Orientations are rotated 0 or 180 degrees, so they retain the width/height of the image 106 | if( (orientation == UIImageOrientationUp) || (orientation == UIImageOrientationDown) || (orientation == UIImageOrientationUpMirrored) || (orientation == UIImageOrientationDownMirrored) ) 107 | { 108 | bmContext = CreateCGBitmapContextForWidthAndHeight( width, height, NULL, kDefaultCGBitmapInfo ); 109 | } 110 | else // The other Orientations are rotated ±90 degrees, so they swap width & height. 111 | { 112 | bmContext = CreateCGBitmapContextForWidthAndHeight( height, width, NULL, kDefaultCGBitmapInfo ); 113 | } 114 | 115 | //CGContextSetInterpolationQuality( bmContext, kCGInterpolationLow ); 116 | CGContextSetBlendMode( bmContext, kCGBlendModeCopy ); // we just want to copy the data 117 | 118 | switch(orientation) 119 | { 120 | case UIImageOrientationDown: // 0th row is at the bottom, and 0th column is on the right - Rotate 180 degrees 121 | transform = CGAffineTransformMake(-1.0, 0.0, 0.0, -1.0, width, height); 122 | break; 123 | 124 | case UIImageOrientationLeft: // 0th row is on the left, and 0th column is the bottom - Rotate -90 degrees 125 | transform = CGAffineTransformMake(0.0, 1.0, -1.0, 0.0, height, 0.0); 126 | break; 127 | 128 | case UIImageOrientationRight: // 0th row is on the right, and 0th column is the top - Rotate 90 degrees 129 | transform = CGAffineTransformMake(0.0, -1.0, 1.0, 0.0, 0.0, width); 130 | break; 131 | 132 | case UIImageOrientationUpMirrored: // 0th row is at the top, and 0th column is on the right - Flip Horizontal 133 | transform = CGAffineTransformMake(-1.0, 0.0, 0.0, 1.0, width, 0.0); 134 | break; 135 | 136 | case UIImageOrientationDownMirrored: // 0th row is at the bottom, and 0th column is on the left - Flip Vertical 137 | transform = CGAffineTransformMake(1.0, 0.0, 0, -1.0, 0.0, height); 138 | break; 139 | 140 | case UIImageOrientationLeftMirrored: // 0th row is on the left, and 0th column is the top - Rotate -90 degrees and Flip Vertical 141 | transform = CGAffineTransformMake(0.0, -1.0, -1.0, 0.0, height, width); 142 | break; 143 | 144 | case UIImageOrientationRightMirrored: // 0th row is on the right, and 0th column is the bottom - Rotate 90 degrees and Flip Vertical 145 | transform = CGAffineTransformMake(0.0, 1.0, 1.0, 0.0, 0.0, 0.0); 146 | break; 147 | 148 | default: 149 | mustTransform = NO; 150 | break; 151 | } 152 | 153 | if( mustTransform ) CGContextConcatCTM( bmContext, transform ); 154 | 155 | CGContextDrawImage( bmContext, CGRectMake(0.0, 0.0, width, height), srcCGImage ); 156 | CGImageRelease( srcCGImage ); 157 | newImage = CGBitmapContextCreateImage( bmContext ); 158 | CFRelease( bmContext ); 159 | 160 | return newImage; 161 | } 162 | 163 | @implementation UIImage (scale) 164 | 165 | -(UIImage*) scaleToSize:(CGSize)toSize 166 | { 167 | UIImage *scaledImg = nil; 168 | float scale = GetScaleForProportionalResize( self.size, toSize, false, false ); 169 | CGImageRef cgImage = CreateCGImageFromUIImageScaled( self, scale ); 170 | 171 | if( cgImage ) 172 | { 173 | scaledImg = [UIImage imageWithCGImage:cgImage]; // autoreleased 174 | CGImageRelease( cgImage ); 175 | } 176 | return scaledImg; 177 | } 178 | 179 | @end 180 | -------------------------------------------------------------------------------- /ios/ImageResizer.h: -------------------------------------------------------------------------------- 1 | #ifdef RCT_NEW_ARCH_ENABLED 2 | #import "RNImageResizerSpec.h" 3 | #else 4 | #import 5 | #endif 6 | 7 | #ifdef RCT_NEW_ARCH_ENABLED 8 | @interface ImageResizer : NSObject 9 | #else 10 | @interface ImageResizer : NSObject 11 | #endif 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /ios/ImageResizer.mm: -------------------------------------------------------------------------------- 1 | #import "ImageResizer.h" 2 | #import 3 | #import 4 | #import 5 | 6 | #if __has_include() 7 | #import 8 | #import 9 | #else 10 | #import "RCTLog.h" 11 | #import "RCTImageLoader.h" 12 | #endif 13 | 14 | NSString *moduleName = @"ImageResizer"; 15 | 16 | @implementation ImageResizer 17 | 18 | @synthesize bridge = _bridge; 19 | 20 | RCT_EXPORT_MODULE() 21 | 22 | RCT_REMAP_METHOD(createResizedImage, uri:(NSString *)uri width:(double)width height:(double)height format:(NSString *)format quality:(double)quality mode:(NSString *)mode onlyScaleDown:(BOOL)onlyScaleDown rotation:(nonnull NSNumber *)rotation outputPath:(NSString *)outputPath keepMeta:(nonnull NSNumber *)keepMeta resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) 23 | { 24 | [self createResizedImage:uri width:width height:height format:format quality:quality mode:mode onlyScaleDown:onlyScaleDown rotation:rotation outputPath:outputPath keepMeta:keepMeta resolve:resolve reject:reject]; 25 | } 26 | 27 | - (void)createResizedImage:(NSString *)uri width:(double)width height:(double)height format:(NSString *)format quality:(double)quality mode:(NSString *)mode onlyScaleDown:(BOOL)onlyScaleDown rotation:(nonnull NSNumber *)rotation outputPath:(NSString *)outputPath keepMeta:(nonnull NSNumber *)keepMeta resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { 28 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 29 | @try { 30 | CGSize newSize = CGSizeMake(width, height); 31 | 32 | //Set image extension 33 | NSString *extension = @"jpg"; 34 | if ([format isEqualToString:@"PNG"]) { 35 | extension = @"png"; 36 | } 37 | 38 | NSString* fullPath; 39 | @try { 40 | fullPath = generateFilePath(extension, outputPath); 41 | } @catch (NSException *exception) { 42 | [NSException raise:moduleName format:@"Invalid output path."]; 43 | } 44 | 45 | RCTImageLoader *loader = [self.bridge moduleForName:@"ImageLoader" lazilyLoadIfNecessary:YES]; 46 | NSURLRequest *request = [RCTConvert NSURLRequest:uri]; 47 | [loader loadImageWithURLRequest:request 48 | size:newSize 49 | scale:1 50 | clipped:NO 51 | resizeMode:RCTResizeModeContain 52 | progressBlock:nil 53 | partialLoadBlock:nil 54 | completionBlock:^(NSError *error, UIImage *image) { 55 | if (error) { 56 | RCTLogError(@"%@", [NSString stringWithFormat:@"Code : %@ / Message : %@", [NSString stringWithFormat: @"%ld", (long)error.code], error.description]); 57 | reject([NSString stringWithFormat: @"%ld", (long)error.code], error.description, nil); 58 | return; 59 | } 60 | NSDictionary * response = transformImage(image, uri, [rotation integerValue], newSize, fullPath, format, (int)quality, [keepMeta boolValue], @{@"mode": mode, @"onlyScaleDown": [NSNumber numberWithBool:onlyScaleDown]}); 61 | resolve(response); 62 | }]; 63 | } @catch (NSException *exception) { 64 | RCTLogError(@"%@", [NSString stringWithFormat:@"Code : %@ / Message : %@", exception.name, exception.reason]); 65 | reject(exception.name, exception.reason, nil); 66 | } 67 | }); 68 | } 69 | 70 | 71 | 72 | bool saveImage(NSString * fullPath, UIImage * image, NSString * format, float quality, NSMutableDictionary *metadata) 73 | { 74 | if(metadata == nil){ 75 | NSData* data = nil; 76 | if ([format isEqualToString:@"JPEG"]) { 77 | data = UIImageJPEGRepresentation(image, quality / 100.0); 78 | } else if ([format isEqualToString:@"PNG"]) { 79 | data = UIImagePNGRepresentation(image); 80 | } 81 | 82 | if (data == nil) { 83 | return NO; 84 | } 85 | 86 | NSFileManager* fileManager = [NSFileManager defaultManager]; 87 | return [fileManager createFileAtPath:fullPath contents:data attributes:nil]; 88 | } 89 | 90 | // process / write metadata together with image data 91 | else{ 92 | 93 | CFStringRef imgType = kUTTypeJPEG; 94 | 95 | if ([format isEqualToString:@"JPEG"]) { 96 | [metadata setObject:@(quality / 100.0) forKey:(__bridge NSString *)kCGImageDestinationLossyCompressionQuality]; 97 | } 98 | else if([format isEqualToString:@"PNG"]){ 99 | imgType = kUTTypePNG; 100 | } 101 | else{ 102 | return NO; 103 | } 104 | 105 | NSMutableData * destData = [NSMutableData data]; 106 | 107 | CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)destData, imgType, 1, NULL); 108 | 109 | @try{ 110 | CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef) metadata); 111 | 112 | // write final image data with metadata to our destination 113 | if (CGImageDestinationFinalize(destination)){ 114 | 115 | NSFileManager* fileManager = [NSFileManager defaultManager]; 116 | return [fileManager createFileAtPath:fullPath contents:destData attributes:nil]; 117 | } 118 | else{ 119 | return NO; 120 | } 121 | } 122 | @finally{ 123 | @try{ 124 | CFRelease(destination); 125 | } 126 | @catch(NSException *exception){ 127 | NSLog(@"Failed to release CGImageDestinationRef: %@", exception); 128 | } 129 | } 130 | } 131 | } 132 | 133 | NSString * generateFilePath(NSString * ext, NSString * outputPath) 134 | { 135 | NSString* directory; 136 | 137 | if ([outputPath length] == 0) { 138 | NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 139 | directory = [paths firstObject]; 140 | } else { 141 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 142 | NSString *documentsDirectory = [paths objectAtIndex:0]; 143 | if ([outputPath hasPrefix:documentsDirectory]) { 144 | directory = outputPath; 145 | } else { 146 | directory = [documentsDirectory stringByAppendingPathComponent:outputPath]; 147 | } 148 | 149 | NSError *error; 150 | [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error]; 151 | if (error) { 152 | NSLog(@"Error creating documents subdirectory: %@", error); 153 | @throw [NSException exceptionWithName:@"InvalidPathException" reason:[NSString stringWithFormat:@"Error creating documents subdirectory: %@", error] userInfo:nil]; 154 | } 155 | } 156 | 157 | NSString* name = [[NSUUID UUID] UUIDString]; 158 | NSString* fullName = [NSString stringWithFormat:@"%@.%@", name, ext]; 159 | NSString* fullPath = [directory stringByAppendingPathComponent:fullName]; 160 | 161 | return fullPath; 162 | } 163 | 164 | UIImage * rotateImage(UIImage *inputImage, float rotationDegrees) 165 | { 166 | 167 | // We want only fixed 0, 90, 180, 270 degree rotations. 168 | const int rotDiv90 = (int)round(rotationDegrees / 90); 169 | const int rotQuadrant = rotDiv90 % 4; 170 | const int rotQuadrantAbs = (rotQuadrant < 0) ? rotQuadrant + 4 : rotQuadrant; 171 | 172 | // Return the input image if no rotation specified. 173 | if (0 == rotQuadrantAbs) { 174 | return inputImage; 175 | } else { 176 | // Rotate the image by 80, 180, 270. 177 | UIImageOrientation orientation = UIImageOrientationUp; 178 | 179 | switch(rotQuadrantAbs) { 180 | case 1: 181 | orientation = UIImageOrientationRight; // 90 deg CW 182 | break; 183 | case 2: 184 | orientation = UIImageOrientationDown; // 180 deg rotation 185 | break; 186 | default: 187 | orientation = UIImageOrientationLeft; // 90 deg CCW 188 | break; 189 | } 190 | 191 | return [[UIImage alloc] initWithCGImage: inputImage.CGImage 192 | scale: 1.0 193 | orientation: orientation]; 194 | } 195 | } 196 | 197 | float getScaleForProportionalResize(CGSize theSize, CGSize intoSize, bool onlyScaleDown, bool maximize) 198 | { 199 | float sx = theSize.width; 200 | float sy = theSize.height; 201 | float dx = intoSize.width; 202 | float dy = intoSize.height; 203 | float scale = 1; 204 | 205 | if( sx != 0 && sy != 0 ) 206 | { 207 | dx = dx / sx; 208 | dy = dy / sy; 209 | 210 | // if maximize is true, take LARGER of the scales, else smaller 211 | if (maximize) { 212 | scale = MAX(dx, dy); 213 | } else { 214 | scale = MIN(dx, dy); 215 | } 216 | 217 | if (onlyScaleDown) { 218 | scale = MIN(scale, 1); 219 | } 220 | } 221 | else 222 | { 223 | scale = 0; 224 | } 225 | return scale; 226 | } 227 | 228 | 229 | // returns a resized image keeping aspect ratio and considering 230 | // any :image scale factor. 231 | // The returned image is an unscaled image (scale = 1.0) 232 | // so no additional scaling math needs to be done to get its pixel dimensions 233 | UIImage* scaleImage (UIImage* image, CGSize toSize, NSString* mode, bool onlyScaleDown) 234 | { 235 | 236 | // Need to do scaling corrections 237 | // based on scale, since UIImage width/height gives us 238 | // a possibly scaled image (dimensions in points) 239 | // Idea taken from RNCamera resize code 240 | CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); 241 | 242 | // using this instead of ImageHelpers allows us to consider 243 | // rotation variations 244 | CGSize newSize; 245 | 246 | if ([mode isEqualToString:@"stretch"]) { 247 | // Distort aspect ratio 248 | int width = toSize.width; 249 | int height = toSize.height; 250 | 251 | if (onlyScaleDown) { 252 | width = MIN(width, imageSize.width); 253 | height = MIN(height, imageSize.height); 254 | } 255 | 256 | newSize = CGSizeMake(width, height); 257 | } else { 258 | // Either "contain" (default) or "cover": preserve aspect ratio 259 | bool maximize = [mode isEqualToString:@"cover"]; 260 | float scale = getScaleForProportionalResize(imageSize, toSize, onlyScaleDown, maximize); 261 | newSize = CGSizeMake(roundf(imageSize.width * scale), roundf(imageSize.height * scale)); 262 | } 263 | 264 | UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0); 265 | [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; 266 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 267 | UIGraphicsEndImageContext(); 268 | return newImage; 269 | } 270 | 271 | // Returns the image's metadata, or nil if failed to retrieve it. 272 | NSMutableDictionary * getImageMeta(NSString * path) 273 | { 274 | if([path hasPrefix:@"assets-library"]) { 275 | 276 | __block NSMutableDictionary* res = nil; 277 | 278 | ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) 279 | { 280 | 281 | NSDictionary *exif = [[myasset defaultRepresentation] metadata]; 282 | res = [exif mutableCopy]; 283 | 284 | }; 285 | 286 | ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init]; 287 | NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 288 | 289 | [assetslibrary assetForURL:url resultBlock:resultblock failureBlock:^(NSError *error) { NSLog(@"error couldn't image from assets library"); }]; 290 | 291 | return res; 292 | 293 | } else { 294 | 295 | NSData* imageData = nil; 296 | 297 | if ([path hasPrefix:@"data:"] || [path hasPrefix:@"file:"]) { 298 | NSURL *imageUrl = [[NSURL alloc] initWithString:path]; 299 | imageData = [NSData dataWithContentsOfURL:imageUrl]; 300 | 301 | } else { 302 | imageData = [NSData dataWithContentsOfFile:path]; 303 | } 304 | 305 | if(imageData == nil){ 306 | NSLog(@"Could not get image file data to extract metadata."); 307 | return nil; 308 | } 309 | 310 | CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)imageData, NULL); 311 | 312 | 313 | if(source != nil){ 314 | 315 | CFDictionaryRef metaRef = CGImageSourceCopyPropertiesAtIndex(source, 0, NULL); 316 | 317 | // release CF image 318 | CFRelease(source); 319 | 320 | CFMutableDictionaryRef metaRefMutable = CFDictionaryCreateMutableCopy(NULL, 0, metaRef); 321 | 322 | // release the source meta ref now that we've copie it 323 | CFRelease(metaRef); 324 | 325 | // bridge CF object so it auto releases 326 | NSMutableDictionary* res = (NSMutableDictionary *)CFBridgingRelease(metaRefMutable); 327 | 328 | return res; 329 | 330 | } 331 | else{ 332 | return nil; 333 | } 334 | 335 | } 336 | } 337 | 338 | NSDictionary * transformImage(UIImage *image, 339 | NSString * originalPath, 340 | int rotation, 341 | CGSize newSize, 342 | NSString* fullPath, 343 | NSString* format, 344 | int quality, 345 | BOOL keepMeta, 346 | NSDictionary* options) 347 | { 348 | if (image == nil) { 349 | [NSException raise:moduleName format:@"Can't retrieve the file from the path."]; 350 | } 351 | 352 | // Rotate image if rotation is specified. 353 | if (0 != (int)rotation) { 354 | image = rotateImage(image, rotation); 355 | if (image == nil) { 356 | [NSException raise:moduleName format:@"Can't rotate the image."]; 357 | } 358 | } 359 | 360 | // Do the resizing 361 | UIImage * scaledImage = scaleImage( 362 | image, 363 | newSize, 364 | options[@"mode"], 365 | [[options objectForKey:@"onlyScaleDown"] boolValue] 366 | ); 367 | 368 | if (scaledImage == nil) { 369 | [NSException raise:moduleName format:@"Can't resize the image."]; 370 | } 371 | 372 | 373 | NSMutableDictionary *metadata = nil; 374 | 375 | // to be consistent with Android, we will only allow JPEG 376 | // to do this. 377 | if(keepMeta && [format isEqualToString:@"JPEG"]){ 378 | 379 | metadata = getImageMeta(originalPath); 380 | 381 | // remove orientation (since we fix it) 382 | // width/height meta is adjusted automatically 383 | // NOTE: This might still leave some stale values due to resize 384 | metadata[(NSString*)kCGImagePropertyOrientation] = @(1); 385 | 386 | } 387 | 388 | // Compress and save the image 389 | if (!saveImage(fullPath, scaledImage, format, quality, metadata)) { 390 | [NSException raise:moduleName format:@"Can't save the image. Check your compression format and your output path"]; 391 | } 392 | 393 | NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:fullPath]; 394 | NSString *fileName = fileUrl.lastPathComponent; 395 | NSError *attributesError = nil; 396 | NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fullPath error:&attributesError]; 397 | NSNumber *fileSize = fileAttributes == nil ? 0 : [fileAttributes objectForKey:NSFileSize]; 398 | NSDictionary *response = @{@"path": fullPath, 399 | @"uri": fileUrl.absoluteString, 400 | @"name": fileName, 401 | @"size": fileSize == nil ? @(0) : fileSize, 402 | @"width": @(scaledImage.size.width), 403 | @"height": @(scaledImage.size.height), 404 | }; 405 | 406 | return response; 407 | } 408 | 409 | // Don't compile this code when we build for the old architecture. 410 | #ifdef RCT_NEW_ARCH_ENABLED 411 | - (std::shared_ptr)getTurboModule: 412 | (const facebook::react::ObjCTurboModule::InitParams &)params 413 | { 414 | return std::make_shared(params); 415 | } 416 | #endif 417 | @end 418 | -------------------------------------------------------------------------------- /ios/ImageResizer.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 5E555C0D2413F4C50049A1A2 /* ImageResizer.m in Sources */ = {isa = PBXBuildFile; fileRef = B3E7B5891CC2AC0600A0062D /* ImageResizer.m */; }; 11 | /* End PBXBuildFile section */ 12 | 13 | /* Begin PBXCopyFilesBuildPhase section */ 14 | 58B511D91A9E6C8500147676 /* CopyFiles */ = { 15 | isa = PBXCopyFilesBuildPhase; 16 | buildActionMask = 2147483647; 17 | dstPath = "include/$(PRODUCT_NAME)"; 18 | dstSubfolderSpec = 16; 19 | files = ( 20 | ); 21 | runOnlyForDeploymentPostprocessing = 0; 22 | }; 23 | /* End PBXCopyFilesBuildPhase section */ 24 | 25 | /* Begin PBXFileReference section */ 26 | 134814201AA4EA6300B7C361 /* libImageResizer.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libImageResizer.a; sourceTree = BUILT_PRODUCTS_DIR; }; 27 | B3E7B5881CC2AC0600A0062D /* ImageResizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ImageResizer.h; sourceTree = ""; }; 28 | B3E7B5891CC2AC0600A0062D /* ImageResizer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ImageResizer.m; sourceTree = ""; }; 29 | /* End PBXFileReference section */ 30 | 31 | /* Begin PBXFrameworksBuildPhase section */ 32 | 58B511D81A9E6C8500147676 /* Frameworks */ = { 33 | isa = PBXFrameworksBuildPhase; 34 | buildActionMask = 2147483647; 35 | files = ( 36 | ); 37 | runOnlyForDeploymentPostprocessing = 0; 38 | }; 39 | /* End PBXFrameworksBuildPhase section */ 40 | 41 | /* Begin PBXGroup section */ 42 | 134814211AA4EA7D00B7C361 /* Products */ = { 43 | isa = PBXGroup; 44 | children = ( 45 | 134814201AA4EA6300B7C361 /* libImageResizer.a */, 46 | ); 47 | name = Products; 48 | sourceTree = ""; 49 | }; 50 | 58B511D21A9E6C8500147676 = { 51 | isa = PBXGroup; 52 | children = ( 53 | B3E7B5881CC2AC0600A0062D /* ImageResizer.h */, 54 | B3E7B5891CC2AC0600A0062D /* ImageResizer.m */, 55 | 134814211AA4EA7D00B7C361 /* Products */, 56 | ); 57 | sourceTree = ""; 58 | }; 59 | /* End PBXGroup section */ 60 | 61 | /* Begin PBXNativeTarget section */ 62 | 58B511DA1A9E6C8500147676 /* ImageResizer */ = { 63 | isa = PBXNativeTarget; 64 | buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "ImageResizer" */; 65 | buildPhases = ( 66 | 58B511D71A9E6C8500147676 /* Sources */, 67 | 58B511D81A9E6C8500147676 /* Frameworks */, 68 | 58B511D91A9E6C8500147676 /* CopyFiles */, 69 | ); 70 | buildRules = ( 71 | ); 72 | dependencies = ( 73 | ); 74 | name = ImageResizer; 75 | productName = RCTDataManager; 76 | productReference = 134814201AA4EA6300B7C361 /* libImageResizer.a */; 77 | productType = "com.apple.product-type.library.static"; 78 | }; 79 | /* End PBXNativeTarget section */ 80 | 81 | /* Begin PBXProject section */ 82 | 58B511D31A9E6C8500147676 /* Project object */ = { 83 | isa = PBXProject; 84 | attributes = { 85 | LastUpgradeCheck = 0920; 86 | ORGANIZATIONNAME = Facebook; 87 | TargetAttributes = { 88 | 58B511DA1A9E6C8500147676 = { 89 | CreatedOnToolsVersion = 6.1.1; 90 | }; 91 | }; 92 | }; 93 | buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "ImageResizer" */; 94 | compatibilityVersion = "Xcode 3.2"; 95 | developmentRegion = English; 96 | hasScannedForEncodings = 0; 97 | knownRegions = ( 98 | English, 99 | en, 100 | ); 101 | mainGroup = 58B511D21A9E6C8500147676; 102 | productRefGroup = 58B511D21A9E6C8500147676; 103 | projectDirPath = ""; 104 | projectRoot = ""; 105 | targets = ( 106 | 58B511DA1A9E6C8500147676 /* ImageResizer */, 107 | ); 108 | }; 109 | /* End PBXProject section */ 110 | 111 | /* Begin PBXSourcesBuildPhase section */ 112 | 58B511D71A9E6C8500147676 /* Sources */ = { 113 | isa = PBXSourcesBuildPhase; 114 | buildActionMask = 2147483647; 115 | files = ( 116 | B3E7B58A1CC2AC0600A0062D /* ImageResizer.m in Sources */, 117 | ); 118 | runOnlyForDeploymentPostprocessing = 0; 119 | }; 120 | /* End PBXSourcesBuildPhase section */ 121 | 122 | /* Begin XCBuildConfiguration section */ 123 | 58B511ED1A9E6C8500147676 /* Debug */ = { 124 | isa = XCBuildConfiguration; 125 | buildSettings = { 126 | ALWAYS_SEARCH_USER_PATHS = NO; 127 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 128 | CLANG_CXX_LIBRARY = "libc++"; 129 | CLANG_ENABLE_MODULES = YES; 130 | CLANG_ENABLE_OBJC_ARC = YES; 131 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 132 | CLANG_WARN_BOOL_CONVERSION = YES; 133 | CLANG_WARN_COMMA = YES; 134 | CLANG_WARN_CONSTANT_CONVERSION = YES; 135 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 136 | CLANG_WARN_EMPTY_BODY = YES; 137 | CLANG_WARN_ENUM_CONVERSION = YES; 138 | CLANG_WARN_INFINITE_RECURSION = YES; 139 | CLANG_WARN_INT_CONVERSION = YES; 140 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 141 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 142 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 143 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 144 | CLANG_WARN_STRICT_PROTOTYPES = YES; 145 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 146 | CLANG_WARN_UNREACHABLE_CODE = YES; 147 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 148 | COPY_PHASE_STRIP = NO; 149 | ENABLE_STRICT_OBJC_MSGSEND = YES; 150 | ENABLE_TESTABILITY = YES; 151 | "EXCLUDED_ARCHS[sdk=*]" = arm64; 152 | GCC_C_LANGUAGE_STANDARD = gnu99; 153 | GCC_DYNAMIC_NO_PIC = NO; 154 | GCC_NO_COMMON_BLOCKS = YES; 155 | GCC_OPTIMIZATION_LEVEL = 0; 156 | GCC_PREPROCESSOR_DEFINITIONS = ( 157 | "DEBUG=1", 158 | "$(inherited)", 159 | ); 160 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 161 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 162 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 163 | GCC_WARN_UNDECLARED_SELECTOR = YES; 164 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 165 | GCC_WARN_UNUSED_FUNCTION = YES; 166 | GCC_WARN_UNUSED_VARIABLE = YES; 167 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 168 | MTL_ENABLE_DEBUG_INFO = YES; 169 | ONLY_ACTIVE_ARCH = YES; 170 | SDKROOT = iphoneos; 171 | }; 172 | name = Debug; 173 | }; 174 | 58B511EE1A9E6C8500147676 /* Release */ = { 175 | isa = XCBuildConfiguration; 176 | buildSettings = { 177 | ALWAYS_SEARCH_USER_PATHS = NO; 178 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 179 | CLANG_CXX_LIBRARY = "libc++"; 180 | CLANG_ENABLE_MODULES = YES; 181 | CLANG_ENABLE_OBJC_ARC = YES; 182 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 183 | CLANG_WARN_BOOL_CONVERSION = YES; 184 | CLANG_WARN_COMMA = YES; 185 | CLANG_WARN_CONSTANT_CONVERSION = YES; 186 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 187 | CLANG_WARN_EMPTY_BODY = YES; 188 | CLANG_WARN_ENUM_CONVERSION = YES; 189 | CLANG_WARN_INFINITE_RECURSION = YES; 190 | CLANG_WARN_INT_CONVERSION = YES; 191 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 192 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 193 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 194 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 195 | CLANG_WARN_STRICT_PROTOTYPES = YES; 196 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 197 | CLANG_WARN_UNREACHABLE_CODE = YES; 198 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 199 | COPY_PHASE_STRIP = YES; 200 | ENABLE_NS_ASSERTIONS = NO; 201 | ENABLE_STRICT_OBJC_MSGSEND = YES; 202 | "EXCLUDED_ARCHS[sdk=*]" = arm64; 203 | GCC_C_LANGUAGE_STANDARD = gnu99; 204 | GCC_NO_COMMON_BLOCKS = YES; 205 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 206 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 207 | GCC_WARN_UNDECLARED_SELECTOR = YES; 208 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 209 | GCC_WARN_UNUSED_FUNCTION = YES; 210 | GCC_WARN_UNUSED_VARIABLE = YES; 211 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 212 | MTL_ENABLE_DEBUG_INFO = NO; 213 | SDKROOT = iphoneos; 214 | VALIDATE_PRODUCT = YES; 215 | }; 216 | name = Release; 217 | }; 218 | 58B511F01A9E6C8500147676 /* Debug */ = { 219 | isa = XCBuildConfiguration; 220 | buildSettings = { 221 | HEADER_SEARCH_PATHS = ( 222 | "$(inherited)", 223 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 224 | "$(SRCROOT)/../../../React/**", 225 | "$(SRCROOT)/../../react-native/React/**", 226 | ); 227 | LIBRARY_SEARCH_PATHS = "$(inherited)"; 228 | OTHER_LDFLAGS = "-ObjC"; 229 | PRODUCT_NAME = ImageResizer; 230 | SKIP_INSTALL = YES; 231 | }; 232 | name = Debug; 233 | }; 234 | 58B511F11A9E6C8500147676 /* Release */ = { 235 | isa = XCBuildConfiguration; 236 | buildSettings = { 237 | HEADER_SEARCH_PATHS = ( 238 | "$(inherited)", 239 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 240 | "$(SRCROOT)/../../../React/**", 241 | "$(SRCROOT)/../../react-native/React/**", 242 | ); 243 | LIBRARY_SEARCH_PATHS = "$(inherited)"; 244 | OTHER_LDFLAGS = "-ObjC"; 245 | PRODUCT_NAME = ImageResizer; 246 | SKIP_INSTALL = YES; 247 | }; 248 | name = Release; 249 | }; 250 | /* End XCBuildConfiguration section */ 251 | 252 | /* Begin XCConfigurationList section */ 253 | 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "ImageResizer" */ = { 254 | isa = XCConfigurationList; 255 | buildConfigurations = ( 256 | 58B511ED1A9E6C8500147676 /* Debug */, 257 | 58B511EE1A9E6C8500147676 /* Release */, 258 | ); 259 | defaultConfigurationIsVisible = 0; 260 | defaultConfigurationName = Release; 261 | }; 262 | 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "ImageResizer" */ = { 263 | isa = XCConfigurationList; 264 | buildConfigurations = ( 265 | 58B511F01A9E6C8500147676 /* Debug */, 266 | 58B511F11A9E6C8500147676 /* Release */, 267 | ); 268 | defaultConfigurationIsVisible = 0; 269 | defaultConfigurationName = Release; 270 | }; 271 | /* End XCConfigurationList section */ 272 | }; 273 | rootObject = 58B511D31A9E6C8500147676 /* Project object */; 274 | } 275 | -------------------------------------------------------------------------------- /lefthook.yml: -------------------------------------------------------------------------------- 1 | pre-commit: 2 | parallel: true 3 | commands: 4 | lint: 5 | files: git diff --name-only @{push} 6 | glob: '*.{js,ts,jsx,tsx}' 7 | run: npx eslint {files} 8 | types: 9 | files: git diff --name-only @{push} 10 | glob: '*.{js,ts, jsx, tsx}' 11 | run: npx tsc --noEmit 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@bam.tech/react-native-image-resizer", 3 | "version": "3.0.11", 4 | "description": "Rescale local images with React Native", 5 | "main": "lib/commonjs/index.js", 6 | "module": "lib/module/index.js", 7 | "types": "lib/typescript/index.d.ts", 8 | "react-native": "src/index.tsx", 9 | "source": "src/index", 10 | "files": [ 11 | "src", 12 | "lib", 13 | "android", 14 | "ios", 15 | "cpp", 16 | "*.podspec", 17 | "!lib/typescript/example", 18 | "!ios/build", 19 | "!android/build", 20 | "!android/gradle", 21 | "!android/gradlew", 22 | "!android/gradlew.bat", 23 | "!android/local.properties", 24 | "!**/__tests__", 25 | "!**/__fixtures__", 26 | "!**/__mocks__", 27 | "!**/.*" 28 | ], 29 | "scripts": { 30 | "test": "jest", 31 | "typescript": "tsc --noEmit", 32 | "lint": "eslint \"**/*.{js,ts,tsx}\"", 33 | "prepare": "bob build", 34 | "release": "release-it", 35 | "example": "yarn --cwd example", 36 | "bootstrap": "yarn example && yarn && yarn example pods", 37 | "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build" 38 | }, 39 | "keywords": [ 40 | "react-native", 41 | "react", 42 | "android", 43 | "ios", 44 | "images", 45 | "image", 46 | "image-resizer", 47 | "scaling", 48 | "scale", 49 | "resize" 50 | ], 51 | "repository": { 52 | "type": "git", 53 | "url": "git+https://github.com/bamlab/react-native-image-resizer.git" 54 | }, 55 | "author": "Florian Rival (http://bam.tech)", 56 | "license": "MIT", 57 | "bugs": { 58 | "url": "https://github.com/bamlab/react-native-image-resizer/issues" 59 | }, 60 | "homepage": "https://github.com/bamlab/react-native-image-resizer#readme", 61 | "publishConfig": { 62 | "registry": "https://registry.npmjs.org/", 63 | "access": "public" 64 | }, 65 | "devDependencies": { 66 | "@evilmartians/lefthook": "^1.2.2", 67 | "@commitlint/config-conventional": "^17.0.2", 68 | "@react-native-community/eslint-config": "^3.0.2", 69 | "@release-it/conventional-changelog": "^5.0.0", 70 | "@types/jest": "^28.1.2", 71 | "@types/react": "~17.0.21", 72 | "@types/react-native": "0.70.0", 73 | "commitlint": "^17.0.2", 74 | "del-cli": "^5.0.0", 75 | "eslint": "^8.4.1", 76 | "eslint-config-prettier": "^8.5.0", 77 | "eslint-plugin-prettier": "^4.0.0", 78 | "jest": "^28.1.1", 79 | "pod-install": "^0.1.0", 80 | "prettier": "^2.0.5", 81 | "react": "18.2.0", 82 | "react-native": "0.71.8", 83 | "react-native-builder-bob": "^0.20.0", 84 | "release-it": "^15.0.0", 85 | "typescript": "^4.5.2" 86 | }, 87 | "resolutions": { 88 | "@types/react": "17.0.21" 89 | }, 90 | "peerDependencies": { 91 | "react": "*", 92 | "react-native": "*" 93 | }, 94 | "engines": { 95 | "node": ">= 16.0.0" 96 | }, 97 | "packageManager": "^yarn@1.22.15", 98 | "jest": { 99 | "preset": "react-native", 100 | "modulePathIgnorePatterns": [ 101 | "/example/node_modules", 102 | "/lib/" 103 | ] 104 | }, 105 | "commitlint": { 106 | "extends": [ 107 | "@commitlint/config-conventional" 108 | ] 109 | }, 110 | "release-it": { 111 | "git": { 112 | "commitMessage": "chore: release ${version}", 113 | "tagName": "v${version}" 114 | }, 115 | "npm": { 116 | "publish": true 117 | }, 118 | "github": { 119 | "release": true 120 | }, 121 | "plugins": { 122 | "@release-it/conventional-changelog": { 123 | "preset": "angular" 124 | } 125 | } 126 | }, 127 | "eslintConfig": { 128 | "root": true, 129 | "extends": [ 130 | "@react-native-community", 131 | "prettier" 132 | ], 133 | "rules": { 134 | "prettier/prettier": [ 135 | "error", 136 | { 137 | "quoteProps": "consistent", 138 | "singleQuote": true, 139 | "tabWidth": 2, 140 | "trailingComma": "es5", 141 | "useTabs": false 142 | } 143 | ] 144 | } 145 | }, 146 | "eslintIgnore": [ 147 | "node_modules/", 148 | "lib/" 149 | ], 150 | "prettier": { 151 | "quoteProps": "consistent", 152 | "singleQuote": true, 153 | "tabWidth": 2, 154 | "trailingComma": "es5", 155 | "useTabs": false 156 | }, 157 | "react-native-builder-bob": { 158 | "source": "src", 159 | "output": "lib", 160 | "targets": [ 161 | "commonjs", 162 | "module", 163 | [ 164 | "typescript", 165 | { 166 | "project": "tsconfig.build.json" 167 | } 168 | ] 169 | ] 170 | }, 171 | "codegenConfig": { 172 | "name": "RNImageResizerSpec", 173 | "type": "modules", 174 | "jsSrcsDir": "src" 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /react-native-image-resizer.podspec: -------------------------------------------------------------------------------- 1 | require "json" 2 | 3 | package = JSON.parse(File.read(File.join(__dir__, "package.json"))) 4 | folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32' 5 | 6 | Pod::Spec.new do |s| 7 | s.name = "react-native-image-resizer" 8 | s.version = package["version"] 9 | s.summary = package["description"] 10 | s.homepage = package["homepage"] 11 | s.license = package["license"] 12 | s.authors = package["author"] 13 | 14 | s.platforms = { :ios => "10.0" } 15 | s.source = { :git => "https://github.com/taboulot/react-native-image-resizer.git", :tag => "#{s.version}" } 16 | 17 | s.source_files = "ios/**/*.{h,m,mm}" 18 | 19 | s.ios.framework = 'AssetsLibrary', 'MobileCoreServices' 20 | 21 | # Don't install the dependencies when we run `pod install` in the old architecture. 22 | if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then 23 | s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1" 24 | s.pod_target_xcconfig = { 25 | "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"", 26 | "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1", 27 | "CLANG_CXX_LANGUAGE_STANDARD" => "c++17" 28 | } 29 | s.dependency "React-Codegen" 30 | s.dependency "RCT-Folly" 31 | s.dependency "RCTRequired" 32 | s.dependency "RCTTypeSafety" 33 | s.dependency "ReactCommon/turbomodule/core" 34 | install_modules_dependencies(s) 35 | else 36 | s.dependency "React-Core" 37 | end 38 | end 39 | 40 | -------------------------------------------------------------------------------- /scripts/bootstrap.js: -------------------------------------------------------------------------------- 1 | const os = require('os'); 2 | const path = require('path'); 3 | const child_process = require('child_process'); 4 | 5 | const root = path.resolve(__dirname, '..'); 6 | const args = process.argv.slice(2); 7 | const options = { 8 | cwd: process.cwd(), 9 | env: process.env, 10 | stdio: 'inherit', 11 | encoding: 'utf-8', 12 | }; 13 | 14 | if (os.type() === 'Windows_NT') { 15 | options.shell = true; 16 | } 17 | 18 | let result; 19 | 20 | if (process.cwd() !== root || args.length) { 21 | // We're not in the root of the project, or additional arguments were passed 22 | // In this case, forward the command to `yarn` 23 | result = child_process.spawnSync('yarn', args, options); 24 | } else { 25 | // If `yarn` is run without arguments, perform bootstrap 26 | result = child_process.spawnSync('yarn', ['bootstrap'], options); 27 | } 28 | 29 | process.exitCode = result.status; 30 | -------------------------------------------------------------------------------- /src/NativeImageResizer.ts: -------------------------------------------------------------------------------- 1 | import type { TurboModule } from 'react-native'; 2 | import { TurboModuleRegistry } from 'react-native'; 3 | 4 | export interface Spec extends TurboModule { 5 | createResizedImage( 6 | uri: string, 7 | width: number, 8 | height: number, 9 | format: string, 10 | quality: number, 11 | mode: string, 12 | onlyScaleDown: boolean, 13 | rotation?: number, 14 | outputPath?: string | null, 15 | keepMeta?: boolean 16 | ): Promise<{ 17 | path: string; 18 | uri: string; 19 | size: number; 20 | name: string; 21 | width: number; 22 | height: number; 23 | base64: string; 24 | }>; 25 | } 26 | 27 | export default TurboModuleRegistry.getEnforcing('ImageResizer'); 28 | -------------------------------------------------------------------------------- /src/__tests__/index.test.tsx: -------------------------------------------------------------------------------- 1 | it.todo('write a test'); 2 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import { NativeModules } from 'react-native'; 2 | import type { Options, ResizeFormat, Response } from './types'; 3 | export type { ResizeFormat, ResizeMode, Response } from './types'; 4 | 5 | // @ts-expect-error 6 | const isTurboModuleEnabled = global.__turboModuleProxy != null; 7 | 8 | const ImageResizer = isTurboModuleEnabled 9 | ? require('./NativeImageResizer').default 10 | : NativeModules.ImageResizer; 11 | 12 | const defaultOptions: Options = { 13 | mode: 'contain', 14 | onlyScaleDown: false, 15 | }; 16 | 17 | function createResizedImage( 18 | uri: string, 19 | width: number, 20 | height: number, 21 | format: ResizeFormat, 22 | quality: number, 23 | rotation: number = 0, 24 | outputPath?: string | null, 25 | keepMeta = false, 26 | options: Options = defaultOptions 27 | ): Promise { 28 | const { mode, onlyScaleDown } = { ...defaultOptions, ...options }; 29 | 30 | return ImageResizer.createResizedImage( 31 | uri, 32 | width, 33 | height, 34 | format, 35 | quality, 36 | mode, 37 | onlyScaleDown, 38 | rotation, 39 | outputPath, 40 | keepMeta 41 | ); 42 | } 43 | 44 | export default { 45 | createResizedImage, 46 | }; 47 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | export interface Response { 2 | path: string; 3 | uri: string; 4 | size: number; 5 | name: string; 6 | width: number; 7 | height: number; 8 | } 9 | 10 | export type ResizeFormat = 'PNG' | 'JPEG' | 'WEBP'; 11 | export type ResizeMode = 'contain' | 'cover' | 'stretch'; 12 | 13 | export type Options = { 14 | /** 15 | * Either `contain` (the default), `cover`, or `stretch`. Similar to 16 | * [react-native 's resizeMode](https://reactnative.dev/docs/image#resizemode) 17 | * 18 | * - `contain` will fit the image within `width` and `height`, 19 | * preserving its ratio 20 | * - `cover` will make sure at least one dimension fits `width` or 21 | * `height`, and the other is larger, also preserving its ratio. 22 | * - `stretch` will resize the image to exactly `width` and `height`. 23 | * 24 | * (Default: 'contain') 25 | */ 26 | mode?: ResizeMode; 27 | /** 28 | * Whether to avoid resizing the image to be larger than the original. 29 | * (Default: false) 30 | */ 31 | onlyScaleDown?: boolean; 32 | }; 33 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "extends": "./tsconfig", 4 | "exclude": ["example"] 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./", 4 | "paths": { 5 | "@bam.tech/react-native-image-resizer": ["./src/index"] 6 | }, 7 | "allowUnreachableCode": false, 8 | "allowUnusedLabels": false, 9 | "esModuleInterop": true, 10 | "importsNotUsedAsValues": "error", 11 | "forceConsistentCasingInFileNames": true, 12 | "jsx": "react", 13 | "lib": ["esnext"], 14 | "module": "esnext", 15 | "moduleResolution": "node", 16 | "noFallthroughCasesInSwitch": true, 17 | "noImplicitReturns": true, 18 | "noImplicitUseStrict": false, 19 | "noStrictGenericChecks": false, 20 | "noUncheckedIndexedAccess": true, 21 | "noUnusedLocals": true, 22 | "noUnusedParameters": true, 23 | "resolveJsonModule": true, 24 | "skipLibCheck": true, 25 | "strict": true, 26 | "target": "esnext" 27 | } 28 | } 29 | --------------------------------------------------------------------------------