├── .nvmrc
├── .watchmanconfig
├── ios
├── .swift-version
├── .swiftformat
├── Exify-Bridging-Header.h
├── Exify.mm
├── .swiftlint.yml
├── Exify.swift
└── ExifyUtils.swift
├── .prettierignore
├── src
├── __tests__
│ └── index.test.tsx
├── index.ts
└── types.ts
├── example
├── jest.config.js
├── src
│ ├── utils
│ │ ├── types.ts
│ │ ├── delay.ts
│ │ ├── index.ts
│ │ ├── json.ts
│ │ └── mockPosition.ts
│ └── App.tsx
├── tsconfig.json
├── assets
│ ├── icon.png
│ ├── splash.png
│ ├── favicon.png
│ └── adaptive-icon.png
├── react-native.config.js
├── index.ts
├── babel.config.js
├── package.json
├── metro.config.js
├── app.json
└── README.md
├── .gitattributes
├── tsconfig.build.json
├── .eslintignore
├── babel.config.js
├── .github
├── FUNDING.yml
├── actions
│ └── setup
│ │ └── action.yml
└── workflows
│ └── ci.yml
├── android
├── src
│ └── main
│ │ ├── AndroidManifestNew.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── lodev09
│ │ └── exify
│ │ ├── ExifyPackage.kt
│ │ ├── ExifyUtils.kt
│ │ ├── ExifyModule.kt
│ │ └── ExifyTags.kt
├── gradle.properties
└── build.gradle
├── .yarnrc.yml
├── scripts
├── swiftformat.sh
└── swiftlint.sh
├── .editorconfig
├── lefthook.yml
├── tsconfig.json
├── LICENSE
├── .gitignore
├── Exify.podspec
├── README.md
├── CONTRIBUTING.md
├── package.json
└── CODE_OF_CONDUCT.md
/.nvmrc:
--------------------------------------------------------------------------------
1 | v18
2 |
--------------------------------------------------------------------------------
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/ios/.swift-version:
--------------------------------------------------------------------------------
1 | 5.2
2 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | .eslintignore
2 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.tsx:
--------------------------------------------------------------------------------
1 | it.todo('write a test')
2 |
--------------------------------------------------------------------------------
/example/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: 'react-native',
3 | }
4 |
--------------------------------------------------------------------------------
/example/src/utils/types.ts:
--------------------------------------------------------------------------------
1 | // lng, lat
2 | export type Position = [number, number]
3 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig",
3 | "exclude": ["example"]
4 | }
5 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | coverage
3 | dist
4 | ios
5 | android
6 | .vscode
7 | .expo
8 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:@react-native/babel-preset'],
3 | }
4 |
--------------------------------------------------------------------------------
/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {},
3 | "extends": "../tsconfig",
4 | }
5 |
--------------------------------------------------------------------------------
/example/assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lodev09/react-native-exify/HEAD/example/assets/icon.png
--------------------------------------------------------------------------------
/example/assets/splash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lodev09/react-native-exify/HEAD/example/assets/splash.png
--------------------------------------------------------------------------------
/example/assets/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lodev09/react-native-exify/HEAD/example/assets/favicon.png
--------------------------------------------------------------------------------
/example/src/utils/delay.ts:
--------------------------------------------------------------------------------
1 | export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
2 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: lodev09
4 | buy_me_a_coffee: lodev09
5 |
--------------------------------------------------------------------------------
/example/assets/adaptive-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lodev09/react-native-exify/HEAD/example/assets/adaptive-icon.png
--------------------------------------------------------------------------------
/android/src/main/AndroidManifestNew.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/example/src/utils/index.ts:
--------------------------------------------------------------------------------
1 | export * from './mockPosition'
2 | export * from './delay'
3 | export * from './types'
4 | export * from './json'
5 |
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | Exify_kotlinVersion=1.7.0
2 | Exify_minSdkVersion=21
3 | Exify_targetSdkVersion=31
4 | Exify_compileSdkVersion=31
5 | Exify_ndkversion=21.4.7075529
6 |
--------------------------------------------------------------------------------
/.yarnrc.yml:
--------------------------------------------------------------------------------
1 | compressionLevel: mixed
2 |
3 | enableGlobalCache: false
4 |
5 | nmHoistingLimits: workspaces
6 |
7 | nodeLinker: node-modules
8 |
9 | plugins:
10 | spec: "@yarnpkg/plugin-workspace-tools"
11 |
--------------------------------------------------------------------------------
/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/utils/json.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Error safe JSON.stringify
3 | */
4 | export const json = (value?: unknown, space = 2): string => {
5 | try {
6 | return JSON.stringify(value, undefined, space)
7 | } catch (e) {
8 | return String(value)
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/ios/.swiftformat:
--------------------------------------------------------------------------------
1 | --allman false
2 | --indent 2
3 | --exclude Pods,Generated
4 |
5 | --disable andOperator
6 | --disable redundantReturn
7 | --disable wrapMultilineStatementBraces
8 | --disable organizeDeclarations
9 |
10 | --enable markTypes
11 |
12 | --enable isEmpty
13 |
--------------------------------------------------------------------------------
/scripts/swiftformat.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if which swiftformat >/dev/null; then
4 | cd ios && swiftformat --quiet .
5 | else
6 | echo "error: SwiftFormat not installed, install with 'brew install swiftformat' (or manually from https://github.com/nicklockwood/SwiftFormat)"
7 | exit 1
8 | fi
9 |
--------------------------------------------------------------------------------
/scripts/swiftlint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if which swiftlint >/dev/null; then
4 | cd ios && swiftlint --quiet --fix && swiftlint --quiet
5 | else
6 | echo "error: SwiftLint not installed, install with 'brew install swiftlint' (or manually from https://github.com/realm/SwiftLint)"
7 | exit 1
8 | fi
9 |
--------------------------------------------------------------------------------
/ios/Exify-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * Created by Jovanni Lo (@lodev09)
4 | * Copyright 2024
5 | *
6 | * This source code is licensed under the MIT license found in the
7 | * LICENSE file in the root directory of this source tree.
8 | */
9 |
10 | #import
11 | #import
12 |
--------------------------------------------------------------------------------
/example/index.ts:
--------------------------------------------------------------------------------
1 | import { registerRootComponent } from 'expo'
2 |
3 | import App from './src/App'
4 |
5 | // registerRootComponent calls AppRegistry.registerComponent('main', () => App);
6 | // It also ensures that whether you load the app in Expo Go or in a native build,
7 | // the environment is set up appropriately
8 | registerRootComponent(App)
9 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/lefthook.yml:
--------------------------------------------------------------------------------
1 | pre-commit:
2 | parallel: true
3 | commands:
4 | lint:
5 | glob: "*.{js,ts,jsx,tsx}"
6 | run: npx eslint --fix {staged_files}
7 | types:
8 | glob: "*.{js,ts, jsx, tsx}"
9 | run: npx tsc --noEmit
10 | prettier:
11 | glob: "*.{js,ts,jsx,tsx}"
12 | run: npx prettier --write {staged_files}
13 | commit-msg:
14 | parallel: true
15 | commands:
16 | commitlint:
17 | run: npx commitlint --edit
18 |
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path')
2 | const pak = require('../package.json')
3 |
4 | // https://medium.com/call-stack/adding-an-example-app-to-your-react-native-library-d23b9741a19c
5 | module.exports = function (api) {
6 | api.cache(true)
7 | return {
8 | presets: ['babel-preset-expo'],
9 | plugins: [
10 | [
11 | 'module-resolver',
12 | {
13 | extensions: ['.tsx', '.ts', '.js', '.json'],
14 | alias: {
15 | [pak.name]: path.join(__dirname, '..', pak.source),
16 | },
17 | },
18 | ],
19 | ],
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/android/src/main/java/com/lodev09/exify/ExifyPackage.kt:
--------------------------------------------------------------------------------
1 | package com.lodev09.exify
2 |
3 | import com.facebook.react.ReactPackage
4 | import com.facebook.react.bridge.NativeModule
5 | import com.facebook.react.bridge.ReactApplicationContext
6 | import com.facebook.react.uimanager.ViewManager
7 |
8 |
9 | class ExifyPackage : ReactPackage {
10 | override fun createNativeModules(reactContext: ReactApplicationContext): List {
11 | return listOf(ExifyModule(reactContext))
12 | }
13 |
14 | override fun createViewManagers(reactContext: ReactApplicationContext): List> {
15 | return emptyList()
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/example/src/utils/mockPosition.ts:
--------------------------------------------------------------------------------
1 | import type { Position } from './types'
2 |
3 | /**
4 | * Mock position in [lng, lat]
5 | */
6 | export const mockPosition = (
7 | center: Position = [-105.358887, 39.113014],
8 | radiusKm = 10
9 | ): Position => {
10 | const centerLng = center[0]
11 | const centerLat = center[1]
12 |
13 | const randomRadius = Math.sqrt(Math.random()) * radiusKm // Ensure even distribution
14 |
15 | // Generate a random angle in radians
16 | const angle = Math.random() * 2 * Math.PI
17 |
18 | // Calculate the new coordinates
19 | const lat = centerLat + (randomRadius / 111.32) * Math.cos(angle)
20 | const lng =
21 | centerLng + (randomRadius / (111.32 * Math.cos(centerLat * (Math.PI / 180)))) * Math.sin(angle)
22 |
23 | return [lng, lat]
24 | }
25 |
--------------------------------------------------------------------------------
/ios/Exify.mm:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * Created by Jovanni Lo (@lodev09)
4 | * Copyright 2024
5 | *
6 | * This source code is licensed under the MIT license found in the
7 | * LICENSE file in the root directory of this source tree.
8 | */
9 |
10 | #import
11 |
12 | @interface RCT_EXTERN_MODULE(Exify, NSObject)
13 |
14 | RCT_EXTERN_METHOD(readAsync:(NSString*)uri
15 | withResolver:(RCTPromiseResolveBlock)resolve
16 | withRejecter:(RCTPromiseRejectBlock)reject)
17 |
18 | RCT_EXTERN_METHOD(writeAsync:(NSString*)uri
19 | withExif:(NSDictionary*)exif
20 | withResolver:(RCTPromiseResolveBlock)resolve
21 | withRejecter:(RCTPromiseRejectBlock)reject)
22 |
23 | + (BOOL)requiresMainQueueSetup
24 | {
25 | return NO;
26 | }
27 |
28 | @end
29 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "rootDir": ".",
4 | "paths": {
5 | "@lodev09/react-native-exify": ["./src/index"]
6 | },
7 | "allowUnreachableCode": false,
8 | "allowUnusedLabels": false,
9 | "esModuleInterop": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "jsx": "react-native",
12 | "lib": ["esnext"],
13 | "module": "esnext",
14 | "moduleResolution": "node",
15 | "noFallthroughCasesInSwitch": true,
16 | "noImplicitReturns": true,
17 | "noImplicitUseStrict": false,
18 | "noStrictGenericChecks": false,
19 | "noUncheckedIndexedAccess": true,
20 | "noUnusedLocals": false,
21 | "noUnusedParameters": true,
22 | "resolveJsonModule": true,
23 | "skipLibCheck": true,
24 | "strict": true,
25 | "target": "esnext",
26 | "verbatimModuleSyntax": true,
27 | "allowJs": false,
28 | "allowSyntheticDefaultImports": true
29 | },
30 | "exclude": ["lib"]
31 | }
32 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "exify-example",
3 | "version": "1.0.0",
4 | "private": true,
5 | "scripts": {
6 | "start": "expo start",
7 | "ios": "expo run:ios",
8 | "android": "expo run:android",
9 | "setup": "npx expo prebuild",
10 | "clean": "yarn setup --clean",
11 | "doctor": "npx expo-doctor"
12 | },
13 | "dependencies": {
14 | "expo": "~50.0.17",
15 | "expo-image": "~1.10.6",
16 | "expo-image-picker": "~14.7.1",
17 | "expo-media-library": "~15.9.2",
18 | "expo-status-bar": "~1.11.1",
19 | "react": "18.2.0",
20 | "react-native": "0.73.6",
21 | "react-native-vision-camera": "^4.0.1"
22 | },
23 | "devDependencies": {
24 | "@babel/core": "^7.20.0",
25 | "@babel/preset-env": "^7.20.0",
26 | "@babel/runtime": "^7.20.0",
27 | "@react-native/metro-config": "^0.73.5",
28 | "babel-plugin-module-resolver": "^5.0.0"
29 | },
30 | "engines": {
31 | "node": ">=18"
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/.github/actions/setup/action.yml:
--------------------------------------------------------------------------------
1 | name: Setup
2 | description: Setup Node.js and install dependencies
3 |
4 | runs:
5 | using: composite
6 | steps:
7 | - name: Setup Node.js
8 | uses: actions/setup-node@v3
9 | with:
10 | node-version-file: .nvmrc
11 |
12 | - name: Enable Corepack
13 | run: corepack enable
14 | shell: bash
15 |
16 | - name: Cache dependencies
17 | id: yarn-cache
18 | uses: actions/cache@v3
19 | with:
20 | path: |
21 | **/node_modules
22 | .yarn/install-state.gz
23 | key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}-${{ hashFiles('**/package.json', '!node_modules/**') }}
24 | restore-keys: |
25 | ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
26 | ${{ runner.os }}-yarn-
27 |
28 | - name: Install dependencies
29 | if: steps.yarn-cache.outputs.cache-hit != 'true'
30 | run: yarn install --immutable
31 | shell: bash
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 lodev09
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 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # Editors
9 | *.sublime-*
10 | .vscode/
11 | jsconfig.json
12 |
13 | # Xcode
14 | #
15 | build/
16 | *.pbxuser
17 | !default.pbxuser
18 | *.mode1v3
19 | !default.mode1v3
20 | *.mode2v3
21 | !default.mode2v3
22 | *.perspectivev3
23 | !default.perspectivev3
24 | xcuserdata
25 | *.xccheckout
26 | *.moved-aside
27 | DerivedData
28 | *.hmap
29 | *.ipa
30 | *.xcuserstate
31 | project.xcworkspace
32 |
33 | # Android/IJ
34 | #
35 | .classpath
36 | .cxx
37 | .gradle
38 | .idea
39 | .project
40 | .settings
41 | local.properties
42 | android.iml
43 |
44 | # Cocoapods
45 | #
46 | example/ios/Pods
47 |
48 | # Ruby
49 | example/vendor/
50 |
51 | # node.js
52 | #
53 | node_modules/
54 | npm-debug.log
55 | yarn-debug.log
56 | yarn-error.log
57 |
58 | # BUCK
59 | buck-out/
60 | \.buckd/
61 | android/app/libs
62 | android/keystores/debug.keystore
63 |
64 | # Yarn
65 | .yarn/*
66 | !.yarn/patches
67 | !.yarn/plugins
68 | !.yarn/releases
69 | !.yarn/sdks
70 | !.yarn/versions
71 |
72 | # Expo
73 | .expo/
74 |
75 | # generated by bob
76 | lib/
77 |
78 | # Example
79 | example/ios
80 | example/android
81 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { NativeModules, Platform } from 'react-native'
2 | import type { ExifTags, ExifyWriteResult } from './types'
3 |
4 | const LINKING_ERROR =
5 | `The package '@lodev09/react-native-exify' doesn't seem to be linked. Make sure: \n\n` +
6 | Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
7 | '- You rebuilt the app after installing the package\n' +
8 | '- You are not using Expo Go\n'
9 |
10 | const Exify = NativeModules.Exify
11 | ? NativeModules.Exify
12 | : new Proxy(
13 | {},
14 | {
15 | get() {
16 | throw new Error(LINKING_ERROR)
17 | },
18 | }
19 | )
20 |
21 | /**
22 | * Write Exif data into an image file.
23 | * @param {string} uri the image uri to write
24 | * @param {ExifTags} tags the exif tags to be written
25 | * @return {Promise} the full exif tags of the image
26 | */
27 | export function writeAsync(uri: string, tags: ExifTags): Promise {
28 | return Exify.writeAsync(uri, tags)
29 | }
30 |
31 | /**
32 | * Read Exif data from an image file.
33 | * @param {string} uri the image uri to read
34 | * @return {Promise} the raw exif tags of the image
35 | */
36 | export function readAsync(uri: string): Promise {
37 | return Exify.readAsync(uri)
38 | }
39 |
40 | export * from './types'
41 |
--------------------------------------------------------------------------------
/android/src/main/java/com/lodev09/exify/ExifyUtils.kt:
--------------------------------------------------------------------------------
1 | package com.lodev09.exify
2 |
3 | import androidx.exifinterface.media.ExifInterface
4 | import com.facebook.react.bridge.Arguments
5 | import com.facebook.react.bridge.ReadableMap
6 | import java.io.InputStream
7 |
8 | object ExifyUtils {
9 | @JvmStatic
10 | fun formatTags(exif: ExifInterface): ReadableMap {
11 | val tags = Arguments.createMap()
12 |
13 | for ((type, tag) in EXIFY_TAGS) {
14 | val attribute = exif.getAttribute(tag)
15 | if (attribute != null && attribute != "") {
16 | when (type) {
17 | "string" -> tags.putString(tag, attribute)
18 | "int" -> tags.putInt(tag, exif.getAttributeInt(tag, 0))
19 | "double" -> tags.putDouble(tag, exif.getAttributeDouble(tag, 0.0))
20 | "array" -> {
21 | val array = Arguments.createArray()
22 | exif.getAttributeRange(tag)?.forEach { value ->
23 | array.pushDouble(value.toDouble())
24 | }
25 |
26 | if (array.size() > 0) tags.putArray(tag, array)
27 | }
28 | }
29 | }
30 | }
31 |
32 | // GPS
33 | exif.latLong?.let {
34 | tags.putDouble(ExifInterface.TAG_GPS_ALTITUDE, exif.getAltitude(0.0))
35 | tags.putDouble(ExifInterface.TAG_GPS_LATITUDE, it[0])
36 | tags.putDouble(ExifInterface.TAG_GPS_LONGITUDE, it[1])
37 | }
38 |
39 | return tags
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/ios/.swiftlint.yml:
--------------------------------------------------------------------------------
1 | disabled_rules:
2 | - identifier_name
3 | - trailing_comma
4 | - todo
5 | - type_body_length
6 | - cyclomatic_complexity
7 | - function_body_length
8 | - for_where
9 | opt_in_rules:
10 | - contains_over_filter_count
11 | - contains_over_filter_is_empty
12 | - contains_over_first_not_nil
13 | - contains_over_range_nil_comparison
14 | - empty_collection_literal
15 | - empty_count
16 | - empty_string
17 | - first_where
18 | - flatmap_over_map_reduce
19 | - last_where
20 | - reduce_boolean
21 | - reduce_into
22 | - yoda_condition
23 | - vertical_whitespace_opening_braces
24 | - vertical_whitespace_closing_braces
25 | - vertical_parameter_alignment_on_call
26 | - untyped_error_in_catch
27 | - unowned_variable_capture
28 | - unavailable_function
29 | - switch_case_on_newline
30 | - static_operator
31 | - strict_fileprivate
32 | - sorted_imports
33 | - sorted_first_last
34 | - required_enum_case
35 | - redundant_type_annotation
36 | - redundant_nil_coalescing
37 | - attributes
38 | - convenience_type
39 | analyzer_rules:
40 | - explicit_self
41 | - unused_declaration
42 | - unused_import
43 |
44 | excluded: # paths to ignore during linting. Takes precedence over `included`.
45 | - Pods
46 |
47 | # Adjust rule numbers
48 | line_length: 160
49 | file_length: 500
50 |
51 | # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging)
52 | reporter: "xcode"
53 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | // Learn more https://docs.expo.io/guides/customizing-metro
2 | const { getDefaultConfig } = require('expo/metro-config')
3 | const { mergeConfig } = require('@react-native/metro-config')
4 | const path = require('path')
5 | const escape = require('escape-string-regexp')
6 | const exclusionList = require('metro-config/src/defaults/exclusionList')
7 | const pak = require('../package.json')
8 |
9 | const root = path.resolve(__dirname, '..')
10 | const modules = Object.keys({ ...pak.peerDependencies })
11 |
12 | /**
13 | * Metro configuration
14 | * https://facebook.github.io/metro/docs/configuration
15 | *
16 | * @type {import('expo/metro-config').MetroConfig}
17 | */
18 | const config = {
19 | watchFolders: [root],
20 |
21 | // We need to make sure that only one version is loaded for peerDependencies
22 | // So we block them at the root, and alias them to the versions in example's node_modules
23 | resolver: {
24 | blacklistRE: exclusionList(
25 | modules.map((m) => new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`))
26 | ),
27 |
28 | extraNodeModules: modules.reduce((acc, name) => {
29 | acc[name] = path.join(__dirname, 'node_modules', name)
30 | return acc
31 | }, {}),
32 | },
33 |
34 | transformer: {
35 | getTransformOptions: async () => ({
36 | transform: {
37 | experimentalImportSupport: false,
38 | inlineRequires: true,
39 | },
40 | }),
41 | },
42 | }
43 |
44 | module.exports = mergeConfig(getDefaultConfig(__dirname), config)
45 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "name": "ExifyExample",
4 | "slug": "ExifyExample",
5 | "version": "1.0.0",
6 | "orientation": "portrait",
7 | "icon": "./assets/icon.png",
8 | "userInterfaceStyle": "dark",
9 | "splash": {
10 | "image": "./assets/splash.png",
11 | "resizeMode": "contain",
12 | "backgroundColor": "#ffffff"
13 | },
14 | "assetBundlePatterns": ["**/*"],
15 | "ios": {
16 | "supportsTablet": true,
17 | "bundleIdentifier": "com.lodev09.exify"
18 | },
19 | "android": {
20 | "adaptiveIcon": {
21 | "foregroundImage": "./assets/adaptive-icon.png",
22 | "backgroundColor": "#ffffff"
23 | },
24 | "package": "com.lodev09.exify"
25 | },
26 | "web": {
27 | "favicon": "./assets/favicon.png"
28 | },
29 | "plugins": [
30 | [
31 | "react-native-vision-camera",
32 | {
33 | "cameraPermissionText": "$(PRODUCT_NAME) needs access to your Camera.",
34 |
35 | // optionally, if you want to record audio:
36 | "enableMicrophonePermission": true,
37 | "microphonePermissionText": "$(PRODUCT_NAME) needs access to your Microphone."
38 | }
39 | ],
40 | [
41 | "expo-media-library",
42 | {
43 | "photosPermission": "Allow $(PRODUCT_NAME) to access your photos.",
44 | "savePhotosPermission": "Allow $(PRODUCT_NAME) to save photos.",
45 | "isAccessMediaLocationEnabled": true
46 | }
47 | ]
48 | ]
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | branches:
8 | - main
9 |
10 | jobs:
11 | lint:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - name: Checkout
15 | uses: actions/checkout@v3
16 |
17 | - name: Setup
18 | uses: ./.github/actions/setup
19 |
20 | - name: Lint files
21 | run: yarn lint
22 |
23 | - name: Typecheck files
24 | run: yarn typecheck
25 |
26 | test:
27 | runs-on: ubuntu-latest
28 | steps:
29 | - name: Checkout
30 | uses: actions/checkout@v3
31 |
32 | - name: Setup
33 | uses: ./.github/actions/setup
34 |
35 | - name: Run unit tests
36 | run: yarn test --maxWorkers=2 --coverage
37 |
38 | verify:
39 | runs-on: ubuntu-latest
40 | steps:
41 | - name: Checkout
42 | uses: actions/checkout@v3
43 |
44 | - name: Setup
45 | uses: ./.github/actions/setup
46 |
47 | - name: Run expo doctor
48 | run: yarn example doctor
49 |
50 | build-library:
51 | runs-on: ubuntu-latest
52 | steps:
53 | - name: Checkout
54 | uses: actions/checkout@v3
55 |
56 | - name: Setup
57 | uses: ./.github/actions/setup
58 |
59 | - name: Build package
60 | run: yarn prepare
61 |
62 | prebuild:
63 | runs-on: macos-14
64 | steps:
65 | - name: Checkout
66 | uses: actions/checkout@v3
67 |
68 | - name: Setup
69 | uses: ./.github/actions/setup
70 |
71 | - name: Prebuild example
72 | run: yarn example setup
73 |
--------------------------------------------------------------------------------
/Exify.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 = "Exify"
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 => min_ios_version_supported }
15 | s.source = { :git => "https://github.com/lodev09/react-native-exify.git", :tag => "#{s.version}" }
16 |
17 | s.source_files = "ios/**/*.{h,m,mm,swift}"
18 |
19 | # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0.
20 | # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79.
21 | if respond_to?(:install_modules_dependencies, true)
22 | install_modules_dependencies(s)
23 | else
24 | s.dependency "React-Core"
25 |
26 | # Don't install the dependencies when we run `pod install` in the old architecture.
27 | if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
28 | s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
29 | s.pod_target_xcconfig = {
30 | "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
31 | "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1",
32 | "CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
33 | }
34 | s.dependency "React-Codegen"
35 | s.dependency "RCT-Folly"
36 | s.dependency "RCTRequired"
37 | s.dependency "RCTTypeSafety"
38 | end
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React Native Exify
2 |
3 | [](https://github.com/lodev09/react-native-exify/actions/workflows/ci.yml)
4 | [](https://codeclimate.com/github/lodev09/react-native-exify/maintainability)
5 | 
6 |
7 | A simple library to read and write image Exif metadata in React Native. Inspired from [this thread](https://github.com/mrousavy/react-native-vision-camera/issues/780).
8 |
9 | ## Features
10 | * ✅ Read Exif data from an image
11 | * ✅ Write Exif data into an image
12 | * ✅ Tags are typed and standardized
13 | * ✅ Works with Expo and bare React Native projects
14 |
15 | ## Installation
16 |
17 | ```sh
18 | yarn add @lodev09/react-native-exify
19 | ```
20 |
21 | ## Usage
22 |
23 | ```ts
24 | import { writeAsync, readAsync, ExifTags } from '@lodev09/react-native-exify';
25 | ```
26 |
27 | ### 🧐 Reading Exif
28 | ```ts
29 | // ...
30 | const uri = 'file://path/to/image.jpg'
31 |
32 | const tags = await readAsync(uri)
33 | console.log(tags)
34 | ```
35 |
36 | ### ✍️ Writing Exif
37 | ```ts
38 | const uri = 'file://path/to/image.jpg'
39 | const newTags: ExifTags = {
40 | GPSLatitude: 69.69,
41 | GPSLongitude: 69.69,
42 | UserComment: 'Someone wrote GPS here!',
43 | }
44 |
45 | const result = await writeAsync(uri, newTags)
46 | console.log(result.tags)
47 | ```
48 |
49 | > [!NOTE]
50 | > On IOS, writing exif into an Asset file will duplicate the image. IOS does not allow writing exif into an Asset file directly.
51 | > If you're getting the photo from a [camera](https://github.com/mrousavy/react-native-vision-camera/), write it into the output file first before saving to the Asset library!
52 |
53 | See [example](example) for more detailed usage.
54 |
55 | ## Contributing
56 | Contributions are welcome!
57 |
58 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
59 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started
2 |
3 | >**Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till "Creating a new application" step, before proceeding.
4 |
5 | ## Step 1: Setup the Application
6 |
7 | ```bash
8 | yarn setup
9 | ```
10 |
11 | This will [prebuild](https://docs.expo.dev/workflow/prebuild/) the project. Prebuild means it will create the native `ios` and `android` for you to get started.
12 |
13 | ## Step 2: Modifying your App
14 |
15 | Now that you have successfully run the app, let's modify it.
16 |
17 | ### ⚛️ TS
18 |
19 | 1. Open `App.tsx` in your text editor of choice and edit some lines.
20 | 2. For **Android**: Press the R key twice or select **"Reload"** from the **Developer Menu** (Ctrl + M (on Window and Linux) or Cmd ⌘ + M (on macOS)) to see your changes!
21 |
22 | For **iOS**: Hit Cmd ⌘ + R in your iOS Simulator to reload the app and see your changes!
23 |
24 | ### 🍎 IOS
25 |
26 | Open `ios/ExifyExample.xcworkspace` in Xcode and run the project. Browse to _Pods -> Development -> Exify_ folder. Modify to your heart's content. You will need to rebuild the project to see your changes.
27 |
28 | ### 🤖 Android
29 |
30 | Open `android` in Android Studio and run the project. Browse to _android -> app -> src -> ... -> MainActivty.kt_. Modify to your heart's content. You will need to rebuild the project to see your changes.
31 |
32 | ## Congratulations! :tada:
33 |
34 | You've successfully run and modified your React Native App. :partying_face:
35 |
36 | ### Now what?
37 |
38 | - If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).
39 | - If you're curious to learn more about React Native, check out the [Introduction to React Native](https://reactnative.dev/docs/getting-started).
40 |
41 | # Troubleshooting
42 |
43 | Try cleaning the project:
44 |
45 | ```bash
46 | yarn clean
47 | ```
48 | If you can't get this to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.
49 |
50 | # Learn More
51 |
52 | To learn more about React Native, take a look at the following resources:
53 |
54 | - [React Native Website](https://reactnative.dev) - learn more about React Native.
55 | - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.
56 | - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.
57 | - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.
58 | - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.
59 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | // Buildscript is evaluated before everything else so we can't use getExtOrDefault
3 | def kotlin_version = rootProject.ext.has("kotlinVersion") ? rootProject.ext.get("kotlinVersion") : project.properties["Exify_kotlinVersion"]
4 |
5 | repositories {
6 | google()
7 | mavenCentral()
8 | }
9 |
10 | dependencies {
11 | classpath "com.android.tools.build:gradle:7.2.1"
12 | // noinspection DifferentKotlinGradleVersion
13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
14 | }
15 | }
16 |
17 | def isNewArchitectureEnabled() {
18 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
19 | }
20 |
21 | apply plugin: "com.android.library"
22 | apply plugin: "kotlin-android"
23 |
24 | if (isNewArchitectureEnabled()) {
25 | apply plugin: "com.facebook.react"
26 | }
27 |
28 | def getExtOrDefault(name) {
29 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["Exify_" + name]
30 | }
31 |
32 | def getExtOrIntegerDefault(name) {
33 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["Exify_" + name]).toInteger()
34 | }
35 |
36 | def supportsNamespace() {
37 | def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
38 | def major = parsed[0].toInteger()
39 | def minor = parsed[1].toInteger()
40 |
41 | // Namespace support was added in 7.3.0
42 | return (major == 7 && minor >= 3) || major >= 8
43 | }
44 |
45 | android {
46 | if (supportsNamespace()) {
47 | namespace "com.lodev09.exify"
48 |
49 | sourceSets {
50 | main {
51 | manifest.srcFile "src/main/AndroidManifestNew.xml"
52 | }
53 | }
54 | }
55 |
56 | compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
57 |
58 | defaultConfig {
59 | minSdkVersion getExtOrIntegerDefault("minSdkVersion")
60 | targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
61 |
62 | }
63 |
64 | buildTypes {
65 | release {
66 | minifyEnabled false
67 | }
68 | }
69 |
70 | lintOptions {
71 | disable "GradleCompatible"
72 | }
73 |
74 | compileOptions {
75 | sourceCompatibility JavaVersion.VERSION_1_8
76 | targetCompatibility JavaVersion.VERSION_1_8
77 | }
78 | }
79 |
80 | repositories {
81 | mavenCentral()
82 | google()
83 | }
84 |
85 | def kotlin_version = getExtOrDefault("kotlinVersion")
86 |
87 | dependencies {
88 | // For < 0.71, this will be from the local maven repo
89 | // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
90 | // noinspection GradleDynamicVersion
91 | implementation "com.facebook.react:react-native:+"
92 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
93 | implementation "androidx.exifinterface:exifinterface:1.3.7"
94 | }
95 |
96 |
--------------------------------------------------------------------------------
/android/src/main/java/com/lodev09/exify/ExifyModule.kt:
--------------------------------------------------------------------------------
1 | package com.lodev09.exify
2 |
3 | import android.content.Context
4 | import android.net.Uri
5 | import androidx.exifinterface.media.ExifInterface
6 | import com.lodev09.exify.ExifyUtils.formatTags
7 | import com.facebook.react.bridge.Arguments
8 | import com.facebook.react.bridge.Promise
9 | import com.facebook.react.bridge.ReactApplicationContext
10 | import com.facebook.react.bridge.ReactContextBaseJavaModule
11 | import com.facebook.react.bridge.ReactMethod
12 | import com.facebook.react.bridge.ReadableMap
13 | import com.facebook.react.bridge.ReadableType
14 | import java.io.IOException
15 |
16 | private const val ERROR_TAG = "E_EXIFY_ERROR"
17 |
18 | class ExifyModule(reactContext: ReactApplicationContext) :
19 | ReactContextBaseJavaModule(reactContext) {
20 |
21 | private val context: Context = reactContext
22 |
23 | override fun getName(): String {
24 | return NAME
25 | }
26 |
27 | @ReactMethod
28 | fun readAsync(uri: String, promise: Promise) {
29 | val photoUri = Uri.parse(uri)
30 |
31 | try {
32 | context.contentResolver.openInputStream(photoUri)?.use {
33 | val tags = formatTags(ExifInterface(it))
34 | it.close()
35 |
36 | promise.resolve(tags)
37 | }
38 | } catch (e: Exception) {
39 | promise.resolve(null)
40 | e.printStackTrace()
41 | }
42 | }
43 |
44 | @ReactMethod
45 | @Throws(IOException::class)
46 | fun writeAsync(uri: String, tags: ReadableMap, promise: Promise) {
47 | val photoUri = Uri.parse(uri)
48 | val params = Arguments.createMap()
49 |
50 | try {
51 | context.contentResolver.openFileDescriptor(photoUri, "rw", null)?.use { parcelDescriptor ->
52 | val exif = ExifInterface(parcelDescriptor.fileDescriptor)
53 |
54 | for ((valType, tag) in EXIFY_TAGS) {
55 | if (!tags.hasKey(tag)) continue
56 |
57 | val type = tags.getType(tag)
58 |
59 | when (type) {
60 | ReadableType.Boolean -> exif.setAttribute(tag, tags.getBoolean(tag).toString())
61 | ReadableType.Number ->
62 | when (valType) {
63 | "double" -> exif.setAttribute(tag, tags.getDouble(tag).toBigDecimal().toPlainString())
64 | else -> exif.setAttribute(tag, tags.getDouble(tag).toInt().toString())
65 | }
66 | ReadableType.String -> exif.setAttribute(tag, tags.getString(tag))
67 | ReadableType.Array -> exif.setAttribute(tag, tags.getArray(tag).toString())
68 | else -> exif.setAttribute(tag, tags.getString(tag))
69 | }
70 | }
71 |
72 | if (
73 | tags.hasKey(ExifInterface.TAG_GPS_LATITUDE) &&
74 | tags.hasKey(ExifInterface.TAG_GPS_LONGITUDE)
75 | ) {
76 | exif.setLatLong(
77 | tags.getDouble(ExifInterface.TAG_GPS_LATITUDE),
78 | tags.getDouble(ExifInterface.TAG_GPS_LONGITUDE)
79 | )
80 | }
81 |
82 | if (tags.hasKey(ExifInterface.TAG_GPS_ALTITUDE)) {
83 | exif.setAltitude(tags.getDouble(ExifInterface.TAG_GPS_ALTITUDE))
84 | }
85 |
86 | params.putString("uri", uri)
87 | params.putMap("tags", formatTags(exif))
88 |
89 | exif.saveAttributes()
90 | promise.resolve(params)
91 | }
92 |
93 | } catch (e: Exception) {
94 | promise.reject(ERROR_TAG, e.message, e)
95 | e.printStackTrace()
96 | }
97 | }
98 |
99 | companion object {
100 | const val NAME = "Exify"
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/ios/Exify.swift:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * Created by Jovanni Lo (@lodev09)
4 | * Copyright 2024
5 | *
6 | * This source code is licensed under the MIT license found in the
7 | * LICENSE file in the root directory of this source tree.
8 | */
9 |
10 | import PhotosUI
11 |
12 | @objc(Exify)
13 | class Exify: NSObject {
14 | func readExif(uri: String, resolve: @escaping RCTPromiseResolveBlock) {
15 | guard let url = URL(string: uri) else {
16 | resolve(nil)
17 | return
18 | }
19 |
20 | readExifTags(from: url) { tags in
21 | resolve(tags)
22 | }
23 | }
24 |
25 | func readExif(assetId: String, resolve: @escaping RCTPromiseResolveBlock) {
26 | guard let asset = getAssetBy(id: assetId) else {
27 | resolve(nil)
28 | return
29 | }
30 |
31 | let imageOptions = PHContentEditingInputRequestOptions()
32 | imageOptions.isNetworkAccessAllowed = true
33 |
34 | asset.requestContentEditingInput(with: imageOptions) { contentInput, _ in
35 | guard let url = contentInput?.fullSizeImageURL else {
36 | resolve(nil)
37 | return
38 | }
39 |
40 | readExifTags(from: url) { tags in
41 | resolve(tags)
42 | }
43 | }
44 | }
45 |
46 | func writeExif(assetId: String, tags: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
47 | guard let asset = getAssetBy(id: assetId) else {
48 | reject("Error", "Cannot retrieve asset.", nil)
49 | return
50 | }
51 |
52 | let imageOptions = PHContentEditingInputRequestOptions()
53 | imageOptions.isNetworkAccessAllowed = true
54 |
55 | asset.requestContentEditingInput(with: imageOptions) { contentInput, _ in
56 | guard let contentInput, let url = contentInput.fullSizeImageURL else {
57 | reject("Error", "Unable to read metadata from asset", nil)
58 | return
59 | }
60 |
61 | updateMetadata(url: url, with: tags) { metadata, data in
62 | guard let metadata, let data else {
63 | reject("Error", "Could not update metadata", nil)
64 | return
65 | }
66 |
67 | do {
68 | try PHPhotoLibrary.shared().performChangesAndWait {
69 | let request = PHAssetCreationRequest.forAsset()
70 | request.addResource(with: .photo, data: data, options: nil)
71 | request.creationDate = Date()
72 |
73 | let newAssetId = request.placeholderForCreatedAsset!.localIdentifier
74 | resolve([
75 | "uri": "ph://\(newAssetId)",
76 | "assetId": newAssetId,
77 | "tags": getExifTags(from: metadata),
78 | ])
79 | }
80 | } catch {
81 | reject("Error", "Could not save to image file", nil)
82 | print(error)
83 | }
84 | }
85 | }
86 | }
87 |
88 | func writeExif(uri: String, tags: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
89 | guard let url = URL(string: uri) else {
90 | reject("Error", "Invalid URL", nil)
91 | return
92 | }
93 |
94 | updateMetadata(url: url, with: tags) { metadata, data in
95 | guard let metadata, let data else {
96 | reject("Error", "Could not update metadata", nil)
97 | return
98 | }
99 |
100 | do {
101 | // Write to the current file
102 | try data.write(to: url, options: .atomic)
103 |
104 | resolve([
105 | "uri": uri,
106 | "tags": getExifTags(from: metadata),
107 | ])
108 | } catch {
109 | reject("Error", "Could not save to image file", nil)
110 | print(error)
111 | }
112 | }
113 | }
114 |
115 | @objc(readAsync:withResolver:withRejecter:)
116 | func readAsync(uri: String, resolve: @escaping RCTPromiseResolveBlock, reject _: @escaping RCTPromiseRejectBlock) {
117 | if uri.starts(with: "ph://") {
118 | let assetId = String(uri[uri.index(uri.startIndex, offsetBy: 5)...])
119 | readExif(assetId: assetId, resolve: resolve)
120 | } else {
121 | readExif(uri: uri, resolve: resolve)
122 | }
123 | }
124 |
125 | @objc(writeAsync:withExif:withResolver:withRejecter:)
126 | func writeAsync(uri: String, tags: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
127 | if uri.starts(with: "ph://") {
128 | let assetId = String(uri[uri.index(uri.startIndex, offsetBy: 5)...])
129 | writeExif(assetId: assetId, tags: tags, resolve: resolve, reject: reject)
130 | } else {
131 | writeExif(uri: uri, tags: tags, resolve: resolve, reject: reject)
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * From Android's ExifInterface Tags
3 | * Normalized for both IOS and Android
4 | */
5 | export interface ExifTags {
6 | SensorLeftBorder?: number
7 | SensorBottomBorder?: number
8 | DefaultCropSize?: number
9 | GPSTrackRef?: string
10 | GPSSpeedRef?: string
11 | GPSSpeed?: number
12 | GPSMapDatum?: string
13 | GPSLatitudeRef?: string
14 | GPSLatitude?: number
15 | GPSDifferential?: number
16 | GPSDestLatitudeRef?: string
17 | GPSDestDistanceRef?: string
18 | GPSHPositioningError?: string
19 | GPSDestDistance?: number
20 | GPSDestBearing?: number
21 | GPSDateStamp?: string
22 | GPSAltitudeRef?: number
23 | GPSAltitude?: number
24 | GPSDestLatitude?: number
25 | GPSImgDirection?: number
26 | GPSDOP?: number
27 | GPSTrack?: number
28 | GPSVersionID?: string
29 | GPSLongitude?: number
30 | GPSDestLongitudeRef?: string
31 | GPSImgDirectionRef?: string
32 | GPSProcessingMethod?: string
33 | GPSMeasureMode?: string
34 | GPSLongitudeRef?: string
35 | GPSSatellites?: string
36 | GPSAreaInformation?: string
37 | GPSDestBearingRef?: string
38 | GPSStatus?: string
39 | GPSTimeStamp?: string
40 | GPSDestLongitude?: number
41 | SensorTopBorder?: number
42 | Copyright?: string
43 | PreviewImageStart?: number
44 | SubSecTimeDigitized?: string
45 | SubSecTime?: string
46 | SubfileType?: number
47 | SpectralSensitivity?: string
48 | SpatialFrequencyResponse?: string
49 | DNGVersion?: number
50 | Sharpness?: number
51 | PixelXDimension?: number
52 | SceneCaptureType?: number
53 | ExposureTime?: number
54 | RelatedSoundFile?: string
55 | AspectFrame?: number
56 | Flash?: number
57 | SceneType?: string
58 | OECF?: string
59 | NewSubfileType?: number
60 | PixelYDimension?: number
61 | MakerNote?: string
62 | ShutterSpeedValue?: number
63 | LightSource?: number
64 | UserComment?: string
65 | GainControl?: number
66 | ISOSpeedRatings?: string
67 | FocalPlaneResolutionUnit?: number
68 | FocalPlaneXResolution?: number
69 | YCbCrCoefficients?: number
70 | FocalLengthIn35mmFilm?: number
71 | LensMake?: string
72 | LensModel?: string
73 | LensSpecification?: number[]
74 | ISO?: number
75 | FlashpixVersion?: number[]
76 | StripOffsets?: number
77 | SensingMethod?: number
78 | FlashEnergy?: number
79 | FocalLength?: number
80 | FNumber?: number
81 | MeteringMode?: number
82 | FocalPlaneYResolution?: number
83 | ExposureBiasValue?: number
84 | ExposureProgram?: number
85 | SubjectDistance?: number
86 | ThumbnailImageLength?: number
87 | Compression?: number
88 | ExposureMode?: number
89 | ExposureIndex?: number
90 | WhiteBalance?: number
91 | DateTimeOriginal?: string
92 | RowsPerStrip?: number
93 | DateTimeDigitized?: string
94 | ExifVersion?: number[]
95 | Saturation?: number
96 | CustomRendered?: number
97 | Contrast?: number
98 | ComponentsConfiguration?: number[]
99 | ColorSpace?: number
100 | SubjectLocation?: number
101 | ThumbnailImageWidth?: number
102 | BrightnessValue?: number
103 | Model?: string
104 | InteroperabilityIndex?: string
105 | CompressedBitsPerPixel?: number
106 | ApertureValue?: number
107 | DeviceSettingDescription?: string
108 | JPEGInterchangeFormat?: number
109 | StripByteCounts?: number
110 | YCbCrSubSampling?: number
111 | DigitalZoomRatio?: number
112 | PreviewImageLength?: number
113 | YCbCrPositioning?: number
114 | FileSource?: string
115 | Artist?: string
116 | Make?: string
117 | CFAPattern?: string
118 | WhitePoint?: number
119 | SamplesPerPixel?: number
120 | SubjectArea?: number[]
121 | JPEGInterchangeFormatLength?: number
122 | ResolutionUnit?: number
123 | PrimaryChromaticities?: number
124 | PlanarConfiguration?: number
125 | TransferFunction?: number
126 | SubSecTimeOriginal?: string
127 | Orientation?: number
128 | PhotometricInterpretation?: number
129 | MaxApertureValue?: number
130 | ImageDescription?: string
131 | SensorRightBorder?: number
132 | YResolution?: number
133 | BitsPerSample?: number
134 | ImageUniqueID?: string
135 | DateTime?: string
136 | ImageWidth?: number
137 | ReferenceBlackWhite?: number
138 | ImageLength?: number
139 | SubjectDistanceRange?: number
140 | XResolution?: number
141 | Software?: string
142 | [key: string]: unknown
143 | }
144 |
145 | /**
146 | * Exify `writeAsync` result data
147 | */
148 | export interface ExifyWriteResult {
149 | /**
150 | * The URI of the image that was written.
151 | * On IOS: If input URI is an asset, this will be new URI created.
152 | *
153 | * This will return exactly the same as the input URI if the input URI is from a local file.
154 | */
155 | uri: string
156 | /**
157 | * A newly created asset ID on IOS.
158 | * Writing exif metadata into an asset file will create a new asset file.
159 | *
160 | * @platform ios
161 | */
162 | assetId?: string
163 | /**
164 | * Normalized Exif tags
165 | */
166 | tags?: ExifTags
167 | }
168 |
--------------------------------------------------------------------------------
/ios/ExifyUtils.swift:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * Created by Jovanni Lo (@lodev09)
4 | * Copyright 2024
5 | *
6 | * This source code is licensed under the MIT license found in the
7 | * LICENSE file in the root directory of this source tree.
8 | */
9 |
10 | import Photos
11 |
12 | func getAssetBy(id: String?) -> PHAsset? {
13 | if let id {
14 | return getAssetsBy(assetIds: [id]).firstObject
15 | }
16 |
17 | return nil
18 | }
19 |
20 | func getAssetsBy(assetIds: [String]) -> PHFetchResult {
21 | let options = PHFetchOptions()
22 |
23 | options.includeHiddenAssets = true
24 | options.includeAllBurstAssets = true
25 | options.fetchLimit = assetIds.count
26 |
27 | return PHAsset.fetchAssets(withLocalIdentifiers: assetIds, options: options)
28 | }
29 |
30 | func addTagEntries(from dictionary: CFString, metadata: NSDictionary, to tags: NSMutableDictionary) {
31 | if let entries = metadata[dictionary] as? [String: Any] {
32 | tags.addEntries(from: entries)
33 | }
34 | }
35 |
36 | func getExifTags(from metadata: NSDictionary) -> [String: Any] {
37 | let tags: NSMutableDictionary = [:]
38 |
39 | // Add root non-dictionary properties
40 | for (key, value) in metadata {
41 | if value as? [String: Any] == nil {
42 | tags[key] = value
43 | }
44 | }
45 |
46 | // Append all {Exif} properties
47 | addTagEntries(from: kCGImagePropertyExifDictionary, metadata: metadata, to: tags)
48 |
49 | // Prefix {GPS} dictionary with "GPS"
50 | if let gps = metadata[kCGImagePropertyGPSDictionary as String] as? [String: Any] {
51 | for (key, value) in gps {
52 | tags["GPS" + key] = value
53 | }
54 | }
55 |
56 | // Include tags from formats
57 | addTagEntries(from: kCGImagePropertyTIFFDictionary, metadata: metadata, to: tags)
58 | addTagEntries(from: kCGImagePropertyPNGDictionary, metadata: metadata, to: tags)
59 |
60 | if #available(iOS 13.0, *) {
61 | addTagEntries(from: kCGImagePropertyHEICSDictionary, metadata: metadata, to: tags)
62 | }
63 |
64 | return tags as? [String: Any] ?? [:]
65 | }
66 |
67 | func readExifTags(from url: URL?, completionHandler: ([String: Any]?) -> Void) {
68 | guard let url, let sourceImage = CGImageSourceCreateWithURL(url as CFURL, nil),
69 | let metadataDict = CGImageSourceCopyPropertiesAtIndex(sourceImage, 0, nil) else {
70 | completionHandler(nil)
71 | return
72 | }
73 |
74 | let tags = getExifTags(from: metadataDict)
75 | completionHandler(tags)
76 | }
77 |
78 | func updateMetadata(url: URL, with tags: [String: Any], completionHanlder: (NSDictionary?, Data?) -> Void) {
79 | guard let cgImageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else {
80 | completionHanlder(nil, nil)
81 | return
82 | }
83 |
84 | let metadataDict = CGImageSourceCopyPropertiesAtIndex(cgImageSource, 0, nil) ?? [:] as CFDictionary
85 | let metadata = NSMutableDictionary(dictionary: metadataDict)
86 |
87 | // Append additional Exif data
88 | let exifDict = metadata[kCGImagePropertyExifDictionary as String] as? NSMutableDictionary
89 | exifDict?.addEntries(from: tags)
90 |
91 | // Handle GPS Tags
92 | var gpsDict = [String: Any]()
93 |
94 | if let latitude = tags["GPSLatitude"] as? Double {
95 | gpsDict[kCGImagePropertyGPSLatitude as String] = abs(latitude)
96 | gpsDict[kCGImagePropertyGPSLatitudeRef as String] = latitude >= 0 ? "N" : "S"
97 | }
98 |
99 | if let longitude = tags["GPSLongitude"] as? Double {
100 | gpsDict[kCGImagePropertyGPSLongitude as String] = abs(longitude)
101 | gpsDict[kCGImagePropertyGPSLongitudeRef as String] = longitude >= 0 ? "E" : "W"
102 | }
103 |
104 | if let altitude = tags["GPSAltitude"] as? Double {
105 | gpsDict[kCGImagePropertyGPSAltitude as String] = abs(altitude)
106 | gpsDict[kCGImagePropertyGPSAltitudeRef as String] = altitude >= 0 ? 0 : 1
107 | }
108 |
109 | if let gpsDate = tags["GPSDateStamp"] as? String {
110 | gpsDict[kCGImagePropertyGPSDateStamp as String] = gpsDate
111 | }
112 |
113 | if let gpsTime = tags["GPSTimeStamp"] as? String {
114 | gpsDict[kCGImagePropertyGPSTimeStamp as String] = gpsTime
115 | }
116 |
117 | if metadata[kCGImagePropertyGPSDictionary as String] == nil {
118 | metadata[kCGImagePropertyGPSDictionary as String] = gpsDict
119 | } else {
120 | if let metadataGpsDict = metadata[kCGImagePropertyGPSDictionary as String] as? NSMutableDictionary {
121 | metadataGpsDict.addEntries(from: gpsDict)
122 | }
123 | }
124 |
125 | metadata.setObject(NSNumber(value: 1), forKey: kCGImageDestinationLossyCompressionQuality as NSString)
126 |
127 | let destinationData = NSMutableData()
128 |
129 | guard let uiImage = UIImage(contentsOfFile: url.path),
130 | let sourceType = CGImageSourceGetType(cgImageSource),
131 | let destination = CGImageDestinationCreateWithData(destinationData, sourceType, 1, nil) else {
132 | completionHanlder(nil, nil)
133 | return
134 | }
135 |
136 | CGImageDestinationAddImage(destination, uiImage.cgImage!, metadata)
137 | CGImageDestinationFinalize(destination)
138 |
139 | completionHanlder(metadata, destinationData as Data)
140 | }
141 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are always welcome, no matter how large or small!
4 |
5 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. Before contributing, please read the [code of conduct](./CODE_OF_CONDUCT.md).
6 |
7 | ## Development workflow
8 |
9 | This project is a monorepo managed using [Yarn workspaces](https://yarnpkg.com/features/workspaces). It contains the following packages:
10 |
11 | - The library package in the root directory.
12 | - An example app in the `example/` directory.
13 |
14 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
15 |
16 | ```sh
17 | yarn
18 | ```
19 |
20 | > Since the project relies on Yarn workspaces, you cannot use [`npm`](https://github.com/npm/cli) for development.
21 |
22 | The [example app](/example/) demonstrates usage of the library. You need to run it to test any changes you make.
23 |
24 | It is configured to use the local version of the library, so any changes you make to the library's source code will be reflected in the example app. Changes to the library's JavaScript code will be reflected in the example app without a rebuild, but native code changes will require a rebuild of the example app.
25 |
26 | If you want to use Android Studio or XCode to edit the native code, you can open the `example/android` or `example/ios` directories respectively in those editors. To edit the Objective-C or Swift files, open `example/ios/ExifyExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-exify`.
27 |
28 | To edit the Java or Kotlin files, open `example/android` in Android studio and find the source files at `react-native-exify` under `Android`.
29 |
30 | You can use various commands from the root directory to work with the project.
31 |
32 | To start the packager:
33 |
34 |
35 | To run the example app on Android:
36 |
37 | ```sh
38 | yarn example android
39 | ```
40 |
41 | To run the example app on iOS:
42 |
43 | ```sh
44 | yarn example ios
45 | ```
46 |
47 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
48 |
49 | ```sh
50 | yarn typecheck
51 | yarn lint
52 | ```
53 |
54 | To fix formatting errors, run the following:
55 |
56 | ```sh
57 | yarn lint --fix
58 | ```
59 |
60 | Remember to add tests for your change if possible. Run the unit tests by:
61 |
62 | ```sh
63 | yarn test
64 | ```
65 |
66 | ### Commit message convention
67 |
68 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
69 |
70 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
71 | - `feat`: new features, e.g. add new method to the module.
72 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
73 | - `docs`: changes into documentation, e.g. add usage example for the module..
74 | - `test`: adding or updating tests, e.g. add integration tests using detox.
75 | - `chore`: tooling changes, e.g. change CI config.
76 |
77 | Our pre-commit hooks verify that your commit message matches this format when committing.
78 |
79 | ### Linting and tests
80 |
81 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
82 |
83 | 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.
84 |
85 | Our pre-commit hooks verify that the linter and tests pass when committing.
86 |
87 | ### Publishing to npm
88 |
89 | 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.
90 |
91 | To publish new versions, run the following:
92 |
93 | ```sh
94 | yarn release
95 | ```
96 |
97 | ### Scripts
98 |
99 | The `package.json` file contains various scripts for common tasks:
100 |
101 | - `yarn`: setup project by installing dependencies.
102 | - `yarn typecheck`: type-check files with TypeScript.
103 | - `yarn lint`: lint files with ESLint.
104 | - `yarn test`: run unit tests with Jest.
105 | - `yarn example start`: start the Metro server for the example app.
106 | - `yarn example android`: run the example app on Android.
107 | - `yarn example ios`: run the example app on iOS.
108 |
109 | ### Sending a pull request
110 |
111 | > **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).
112 |
113 | When you're sending a pull request:
114 |
115 | - Prefer small pull requests focused on one change.
116 | - Verify that linters and tests are passing.
117 | - Review the documentation to make sure it looks good.
118 | - Follow the pull request template when opening a pull request.
119 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
120 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@lodev09/react-native-exify",
3 | "version": "0.2.7",
4 | "description": "Read and write exif data into an image 🏷️",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/src/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "src",
12 | "lib",
13 | "android",
14 | "ios",
15 | "cpp",
16 | "*.podspec",
17 | "!ios/build",
18 | "!android/build",
19 | "!android/gradle",
20 | "!android/gradlew",
21 | "!android/gradlew.bat",
22 | "!android/local.properties",
23 | "!**/__tests__",
24 | "!**/__fixtures__",
25 | "!**/__mocks__",
26 | "!**/.*"
27 | ],
28 | "scripts": {
29 | "example": "yarn workspace exify-example",
30 | "test": "jest",
31 | "typecheck": "tsc --noEmit",
32 | "lint": "eslint --fix \"**/*.{js,ts,tsx}\"",
33 | "format": "prettier --write \"**/*.{js,ts,tsx}\"",
34 | "tidy": "yarn typecheck && yarn lint && yarn format && scripts/swiftlint.sh && scripts/swiftformat.sh",
35 | "clean": "del-cli android/build lib && yarn workspace exify-example clean",
36 | "prepare": "bob build",
37 | "release": "release-it"
38 | },
39 | "keywords": [
40 | "exif",
41 | "exif-gps",
42 | "image-exif",
43 | "react-native",
44 | "ios",
45 | "android"
46 | ],
47 | "repository": {
48 | "type": "git",
49 | "url": "git+https://github.com/lodev09/react-native-exify.git"
50 | },
51 | "author": "lodev09 (https://github.com/lodev09)",
52 | "license": "MIT",
53 | "bugs": {
54 | "url": "https://github.com/lodev09/react-native-exify/issues"
55 | },
56 | "homepage": "https://github.com/lodev09/react-native-exify#readme",
57 | "publishConfig": {
58 | "registry": "https://registry.npmjs.org/"
59 | },
60 | "devDependencies": {
61 | "@commitlint/config-conventional": "^19.0.3",
62 | "@evilmartians/lefthook": "^1.6.5",
63 | "@react-native/eslint-config": "^0.73.2",
64 | "@release-it/conventional-changelog": "^8.0.1",
65 | "@types/jest": "^29.5.12",
66 | "@types/react": "^18.2.64",
67 | "@typescript-eslint/eslint-plugin": "^7.1.1",
68 | "@typescript-eslint/parser": "^7.1.1",
69 | "commitlint": "^19.0.3",
70 | "del-cli": "^5.1.0",
71 | "eslint": "^8.57.0",
72 | "eslint-config-prettier": "^9.1.0",
73 | "eslint-config-standard": "^17.1.0",
74 | "eslint-plugin-import": "^2.29.1",
75 | "eslint-plugin-n": "^16.6.2",
76 | "eslint-plugin-prettier": "^5.1.3",
77 | "eslint-plugin-promise": "^6.1.1",
78 | "jest": "^29.7.0",
79 | "prettier": "^3.2.5",
80 | "react": "^18.2.0",
81 | "react-native": "^0.73.5",
82 | "react-native-builder-bob": "^0.23.2",
83 | "release-it": "^17.1.1",
84 | "typescript": "~5.3.3"
85 | },
86 | "resolutions": {
87 | "@types/react": "^18.2.44"
88 | },
89 | "peerDependencies": {
90 | "react": "*",
91 | "react-native": "*"
92 | },
93 | "workspaces": [
94 | "example"
95 | ],
96 | "packageManager": "yarn@4.1.1",
97 | "jest": {
98 | "preset": "react-native",
99 | "modulePathIgnorePatterns": [
100 | "/example/node_modules",
101 | "/lib/"
102 | ]
103 | },
104 | "commitlint": {
105 | "extends": [
106 | "@commitlint/config-conventional"
107 | ]
108 | },
109 | "release-it": {
110 | "git": {
111 | "commitMessage": "chore: release ${version}",
112 | "tagName": "v${version}"
113 | },
114 | "npm": {
115 | "publish": true
116 | },
117 | "github": {
118 | "release": true,
119 | "comments": {
120 | "submit": true,
121 | "issue": ":rocket: _This issue has been resolved in v${version}. See [${releaseName}](${releaseUrl}) for release notes._",
122 | "pr": ":rocket: _This pull request is included in v${version}. See [${releaseName}](${releaseUrl}) for release notes._"
123 | }
124 | },
125 | "plugins": {
126 | "@release-it/conventional-changelog": {
127 | "preset": "angular"
128 | }
129 | }
130 | },
131 | "eslintConfig": {
132 | "root": true,
133 | "ignorePatterns": [
134 | "lib"
135 | ],
136 | "extends": [
137 | "plugin:@typescript-eslint/recommended",
138 | "eslint:recommended",
139 | "plugin:react/recommended",
140 | "plugin:react-native/all",
141 | "standard",
142 | "prettier"
143 | ],
144 | "globals": {
145 | "it": false
146 | },
147 | "rules": {
148 | "@typescript-eslint/no-var-requires": 0,
149 | "@typescript-eslint/no-unused-vars": [
150 | "error",
151 | {
152 | "argsIgnorePattern": "^_",
153 | "varsIgnorePattern": "^_"
154 | }
155 | ],
156 | "no-unused-vars": 0
157 | },
158 | "settings": {
159 | "react": {
160 | "pragma": "React",
161 | "version": "detect"
162 | }
163 | }
164 | },
165 | "prettier": {
166 | "quoteProps": "consistent",
167 | "singleQuote": true,
168 | "tabWidth": 2,
169 | "trailingComma": "es5",
170 | "useTabs": false,
171 | "printWidth": 100,
172 | "semi": false
173 | },
174 | "react-native-builder-bob": {
175 | "source": "src",
176 | "output": "lib",
177 | "targets": [
178 | "commonjs",
179 | "module",
180 | [
181 | "typescript",
182 | {
183 | "project": "tsconfig.build.json"
184 | }
185 | ]
186 | ]
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 | # Contributor Covenant Code of Conduct
3 |
4 | ## Our Pledge
5 |
6 | We as members, contributors, and leaders pledge to make participation in our
7 | community a harassment-free experience for everyone, regardless of age, body
8 | size, visible or invisible disability, ethnicity, sex characteristics, gender
9 | identity and expression, level of experience, education, socio-economic status,
10 | nationality, personal appearance, race, caste, color, religion, or sexual
11 | identity and orientation.
12 |
13 | We pledge to act and interact in ways that contribute to an open, welcoming,
14 | diverse, inclusive, and healthy community.
15 |
16 | ## Our Standards
17 |
18 | Examples of behavior that contributes to a positive environment for our
19 | community include:
20 |
21 | * Demonstrating empathy and kindness toward other people
22 | * Being respectful of differing opinions, viewpoints, and experiences
23 | * Giving and gracefully accepting constructive feedback
24 | * Accepting responsibility and apologizing to those affected by our mistakes,
25 | and learning from the experience
26 | * Focusing on what is best not just for us as individuals, but for the overall
27 | community
28 |
29 | Examples of unacceptable behavior include:
30 |
31 | * The use of sexualized language or imagery, and sexual attention or advances of
32 | any kind
33 | * Trolling, insulting or derogatory comments, and personal or political attacks
34 | * Public or private harassment
35 | * Publishing others' private information, such as a physical or email address,
36 | without their explicit permission
37 | * Other conduct which could reasonably be considered inappropriate in a
38 | professional setting
39 |
40 | ## Enforcement Responsibilities
41 |
42 | Community leaders are responsible for clarifying and enforcing our standards of
43 | acceptable behavior and will take appropriate and fair corrective action in
44 | response to any behavior that they deem inappropriate, threatening, offensive,
45 | or harmful.
46 |
47 | Community leaders have the right and responsibility to remove, edit, or reject
48 | comments, commits, code, wiki edits, issues, and other contributions that are
49 | not aligned to this Code of Conduct, and will communicate reasons for moderation
50 | decisions when appropriate.
51 |
52 | ## Scope
53 |
54 | This Code of Conduct applies within all community spaces, and also applies when
55 | an individual is officially representing the community in public spaces.
56 | Examples of representing our community include using an official e-mail address,
57 | posting via an official social media account, or acting as an appointed
58 | representative at an online or offline event.
59 |
60 | ## Enforcement
61 |
62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
63 | reported to the community leaders responsible for enforcement at
64 | [INSERT CONTACT METHOD].
65 | All complaints will be reviewed and investigated promptly and fairly.
66 |
67 | All community leaders are obligated to respect the privacy and security of the
68 | reporter of any incident.
69 |
70 | ## Enforcement Guidelines
71 |
72 | Community leaders will follow these Community Impact Guidelines in determining
73 | the consequences for any action they deem in violation of this Code of Conduct:
74 |
75 | ### 1. Correction
76 |
77 | **Community Impact**: Use of inappropriate language or other behavior deemed
78 | unprofessional or unwelcome in the community.
79 |
80 | **Consequence**: A private, written warning from community leaders, providing
81 | clarity around the nature of the violation and an explanation of why the
82 | behavior was inappropriate. A public apology may be requested.
83 |
84 | ### 2. Warning
85 |
86 | **Community Impact**: A violation through a single incident or series of
87 | actions.
88 |
89 | **Consequence**: A warning with consequences for continued behavior. No
90 | interaction with the people involved, including unsolicited interaction with
91 | those enforcing the Code of Conduct, for a specified period of time. This
92 | includes avoiding interactions in community spaces as well as external channels
93 | like social media. Violating these terms may lead to a temporary or permanent
94 | ban.
95 |
96 | ### 3. Temporary Ban
97 |
98 | **Community Impact**: A serious violation of community standards, including
99 | sustained inappropriate behavior.
100 |
101 | **Consequence**: A temporary ban from any sort of interaction or public
102 | communication with the community for a specified period of time. No public or
103 | private interaction with the people involved, including unsolicited interaction
104 | with those enforcing the Code of Conduct, is allowed during this period.
105 | Violating these terms may lead to a permanent ban.
106 |
107 | ### 4. Permanent Ban
108 |
109 | **Community Impact**: Demonstrating a pattern of violation of community
110 | standards, including sustained inappropriate behavior, harassment of an
111 | individual, or aggression toward or disparagement of classes of individuals.
112 |
113 | **Consequence**: A permanent ban from any sort of public interaction within the
114 | community.
115 |
116 | ## Attribution
117 |
118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119 | version 2.1, available at
120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121 |
122 | Community Impact Guidelines were inspired by
123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124 |
125 | For answers to common questions about this code of conduct, see the FAQ at
126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127 | [https://www.contributor-covenant.org/translations][translations].
128 |
129 | [homepage]: https://www.contributor-covenant.org
130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131 | [Mozilla CoC]: https://github.com/mozilla/diversity
132 | [FAQ]: https://www.contributor-covenant.org/faq
133 | [translations]: https://www.contributor-covenant.org/translations
134 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useRef, useState } from 'react'
2 | import {
3 | StyleSheet,
4 | Text,
5 | TouchableOpacity,
6 | View,
7 | type TextStyle,
8 | type ViewStyle,
9 | } from 'react-native'
10 | import { StatusBar } from 'expo-status-bar'
11 | import * as Exify from '@lodev09/react-native-exify'
12 | import * as ImagePicker from 'expo-image-picker'
13 | import { Image, type ImageStyle } from 'expo-image'
14 | import {
15 | Camera,
16 | useCameraDevice,
17 | useCameraPermission,
18 | useMicrophonePermission,
19 | } from 'react-native-vision-camera'
20 | import * as MediaLibrary from 'expo-media-library'
21 |
22 | import { json, mockPosition } from './utils'
23 |
24 | const SPACE = 16
25 |
26 | const CAPTURE_BUTTON_SIZE = 64
27 | const CAPTURE_WRAPPER_SIZE = CAPTURE_BUTTON_SIZE + SPACE
28 |
29 | const App = () => {
30 | const camera = useRef(null)
31 |
32 | const [previewUri, setPreviewUri] = useState()
33 |
34 | const cameraPermission = useCameraPermission()
35 | const microphonePermission = useMicrophonePermission()
36 | const [mediaLibraryPermission, requestMediaLibraryPermission] = MediaLibrary.usePermissions()
37 |
38 | const device = useCameraDevice('back')
39 |
40 | const readExif = async (uri: string) => {
41 | const result = await Exify.readAsync(uri)
42 | console.log(json(result))
43 | }
44 |
45 | const writeExif = async (uri: string) => {
46 | const position = mockPosition()
47 |
48 | // Add additional exif e.g. GPS
49 | const result = await Exify.writeAsync(uri, {
50 | GPSLatitude: position[1],
51 | GPSLongitude: position[0],
52 | GPSTimeStamp: '10:10:10',
53 | GPSDateStamp: '2024:10:10',
54 | UserComment: 'Exif updated via react-native-exify',
55 | })
56 |
57 | console.log(json(result))
58 | }
59 |
60 | const takePhoto = async () => {
61 | try {
62 | const photo = await camera.current?.takePhoto()
63 | if (photo) {
64 | const photoUri = `file://${photo.path}`
65 |
66 | // Write asset to the photo
67 | await writeExif(photoUri)
68 |
69 | const permission = await MediaLibrary.requestPermissionsAsync()
70 | if (permission.granted) {
71 | const asset = await MediaLibrary.createAssetAsync(photoUri)
72 | setPreviewUri(asset.uri)
73 | }
74 | }
75 | } catch (e) {
76 | console.error(e)
77 | }
78 | }
79 |
80 | const openLibrary = async () => {
81 | try {
82 | const result = await ImagePicker.launchImageLibraryAsync({
83 | mediaTypes: ImagePicker.MediaTypeOptions.All,
84 | allowsMultipleSelection: true,
85 | selectionLimit: 1,
86 | })
87 |
88 | if (!result.canceled) {
89 | const asset = result.assets[0]
90 | if (asset?.assetId) {
91 | // Get asset uri first to get full exif information
92 | const assetInfo = await MediaLibrary.getAssetInfoAsync(asset.assetId)
93 |
94 | await readExif(assetInfo.uri)
95 | // await writeExif(assetInfo.uri)
96 | } else if (asset?.uri) {
97 | // Read from picker temp file
98 | // less exif when using expo-media-library
99 | await readExif(asset.uri)
100 | } else {
101 | console.warn('URI not found!')
102 | }
103 | }
104 | } catch (e) {
105 | console.error(e)
106 | }
107 | }
108 |
109 | useEffect(() => {
110 | ;(async () => {
111 | await cameraPermission.requestPermission()
112 | await microphonePermission.requestPermission()
113 | await requestMediaLibraryPermission()
114 | })()
115 | }, [])
116 |
117 | useEffect(() => {
118 | ;(async () => {
119 | if (mediaLibraryPermission?.granted) {
120 | const result = await MediaLibrary.getAssetsAsync({ first: 1, mediaType: 'photo' })
121 | if (result.assets.length) {
122 | setPreviewUri(result.assets[0]?.uri)
123 | }
124 | }
125 | })()
126 | }, [mediaLibraryPermission])
127 |
128 | if (!device) {
129 | return (
130 |
131 | Only available on your fully paid iPhone or Android!
132 |
133 | )
134 | }
135 |
136 | return (
137 |
138 |
139 |
140 | {cameraPermission.hasPermission ? (
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 | ) : (
150 | ⚠️ We need access to your Camera
151 | )}
152 |
153 | )
154 | }
155 |
156 | const $container: ViewStyle = {
157 | flex: 1,
158 | backgroundColor: '#0d0e11',
159 | alignItems: 'center',
160 | justifyContent: 'center',
161 | }
162 |
163 | const $controlsContainer: ViewStyle = {
164 | flexDirection: 'row',
165 | alignItems: 'center',
166 | justifyContent: 'center',
167 | position: 'absolute',
168 | bottom: SPACE * 4,
169 | width: '100%',
170 | }
171 |
172 | const $image: ImageStyle = {
173 | width: '100%',
174 | height: '100%',
175 | }
176 |
177 | const $library: ImageStyle = {
178 | position: 'absolute',
179 | left: SPACE * 2,
180 | width: SPACE * 3,
181 | height: SPACE * 3,
182 | borderRadius: 4,
183 | marginRight: SPACE,
184 | borderWidth: 2,
185 | borderColor: 'white',
186 | }
187 |
188 | const $captureWrapper: ViewStyle = {
189 | alignSelf: 'center',
190 | height: CAPTURE_WRAPPER_SIZE,
191 | width: CAPTURE_WRAPPER_SIZE,
192 | borderRadius: CAPTURE_WRAPPER_SIZE / 2,
193 | alignItems: 'center',
194 | justifyContent: 'center',
195 | borderWidth: 2,
196 | borderColor: 'white',
197 | }
198 |
199 | const $captureButton: ViewStyle = {
200 | backgroundColor: '#ffffff',
201 | height: CAPTURE_BUTTON_SIZE,
202 | width: CAPTURE_BUTTON_SIZE,
203 | borderRadius: CAPTURE_BUTTON_SIZE / 2,
204 | }
205 |
206 | const $text: TextStyle = {
207 | color: '#ffffff',
208 | fontWeight: 'bold',
209 | }
210 |
211 | export default App
212 |
--------------------------------------------------------------------------------
/android/src/main/java/com/lodev09/exify/ExifyTags.kt:
--------------------------------------------------------------------------------
1 | package com.lodev09.exify
2 | import androidx.exifinterface.media.ExifInterface
3 |
4 | /**
5 | * Supported Exif Tags
6 | * Note: Latitude, Longitude and Altitude tags are updated separately
7 | */
8 | val EXIFY_TAGS = arrayOf(
9 | arrayOf("string", ExifInterface.TAG_ARTIST),
10 | arrayOf("int", ExifInterface.TAG_BITS_PER_SAMPLE),
11 | arrayOf("int", ExifInterface.TAG_COMPRESSION),
12 | arrayOf("string", ExifInterface.TAG_COPYRIGHT),
13 | arrayOf("string", ExifInterface.TAG_DATETIME),
14 | arrayOf("string", ExifInterface.TAG_IMAGE_DESCRIPTION),
15 | arrayOf("int", ExifInterface.TAG_IMAGE_LENGTH),
16 | arrayOf("int", ExifInterface.TAG_IMAGE_WIDTH),
17 | arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT),
18 | arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH),
19 | arrayOf("string", ExifInterface.TAG_MAKE),
20 | arrayOf("string", ExifInterface.TAG_MODEL),
21 | arrayOf("int", ExifInterface.TAG_ORIENTATION),
22 | arrayOf("int", ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION),
23 | arrayOf("int", ExifInterface.TAG_PLANAR_CONFIGURATION),
24 | arrayOf("double", ExifInterface.TAG_PRIMARY_CHROMATICITIES),
25 | arrayOf("double", ExifInterface.TAG_REFERENCE_BLACK_WHITE),
26 | arrayOf("int", ExifInterface.TAG_RESOLUTION_UNIT),
27 | arrayOf("int", ExifInterface.TAG_ROWS_PER_STRIP),
28 | arrayOf("int", ExifInterface.TAG_SAMPLES_PER_PIXEL),
29 | arrayOf("string", ExifInterface.TAG_SOFTWARE),
30 | arrayOf("int", ExifInterface.TAG_STRIP_BYTE_COUNTS),
31 | arrayOf("int", ExifInterface.TAG_STRIP_OFFSETS),
32 | arrayOf("int", ExifInterface.TAG_TRANSFER_FUNCTION),
33 | arrayOf("double", ExifInterface.TAG_WHITE_POINT),
34 | arrayOf("double", ExifInterface.TAG_X_RESOLUTION),
35 | arrayOf("double", ExifInterface.TAG_Y_CB_CR_COEFFICIENTS),
36 | arrayOf("int", ExifInterface.TAG_Y_CB_CR_POSITIONING),
37 | arrayOf("int", ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING),
38 | arrayOf("double", ExifInterface.TAG_Y_RESOLUTION),
39 | arrayOf("double", ExifInterface.TAG_APERTURE_VALUE),
40 | arrayOf("double", ExifInterface.TAG_BRIGHTNESS_VALUE),
41 | arrayOf("string", ExifInterface.TAG_CFA_PATTERN),
42 | arrayOf("int", ExifInterface.TAG_COLOR_SPACE),
43 | arrayOf("array", ExifInterface.TAG_COMPONENTS_CONFIGURATION),
44 | arrayOf("double", ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL),
45 | arrayOf("int", ExifInterface.TAG_CONTRAST),
46 | arrayOf("int", ExifInterface.TAG_CUSTOM_RENDERED),
47 | arrayOf("string", ExifInterface.TAG_DATETIME_DIGITIZED),
48 | arrayOf("string", ExifInterface.TAG_DATETIME_ORIGINAL),
49 | arrayOf("string", ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION),
50 | arrayOf("double", ExifInterface.TAG_DIGITAL_ZOOM_RATIO),
51 | arrayOf("array", ExifInterface.TAG_EXIF_VERSION),
52 | arrayOf("double", ExifInterface.TAG_EXPOSURE_BIAS_VALUE),
53 | arrayOf("double", ExifInterface.TAG_EXPOSURE_INDEX),
54 | arrayOf("int", ExifInterface.TAG_EXPOSURE_MODE),
55 | arrayOf("int", ExifInterface.TAG_EXPOSURE_PROGRAM),
56 | arrayOf("double", ExifInterface.TAG_EXPOSURE_TIME),
57 | arrayOf("double", ExifInterface.TAG_F_NUMBER),
58 | arrayOf("string", ExifInterface.TAG_FILE_SOURCE),
59 | arrayOf("int", ExifInterface.TAG_FLASH),
60 | arrayOf("double", ExifInterface.TAG_FLASH_ENERGY),
61 | arrayOf("array", ExifInterface.TAG_FLASHPIX_VERSION),
62 | arrayOf("double", ExifInterface.TAG_FOCAL_LENGTH),
63 | arrayOf("string", ExifInterface.TAG_LENS_MAKE),
64 | arrayOf("string", ExifInterface.TAG_LENS_MODEL),
65 | arrayOf("array", ExifInterface.TAG_LENS_SPECIFICATION),
66 | arrayOf("int", ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM),
67 | arrayOf("int", ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT),
68 | arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION),
69 | arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION),
70 | arrayOf("int", ExifInterface.TAG_GAIN_CONTROL),
71 | arrayOf("string", ExifInterface.TAG_ISO_SPEED_RATINGS),
72 | arrayOf("string", ExifInterface.TAG_IMAGE_UNIQUE_ID),
73 | arrayOf("int", ExifInterface.TAG_LIGHT_SOURCE),
74 | arrayOf("string", ExifInterface.TAG_MAKER_NOTE),
75 | arrayOf("double", ExifInterface.TAG_MAX_APERTURE_VALUE),
76 | arrayOf("int", ExifInterface.TAG_METERING_MODE),
77 | arrayOf("int", ExifInterface.TAG_NEW_SUBFILE_TYPE),
78 | arrayOf("string", ExifInterface.TAG_OECF),
79 | arrayOf("int", ExifInterface.TAG_PIXEL_X_DIMENSION),
80 | arrayOf("int", ExifInterface.TAG_PIXEL_Y_DIMENSION),
81 | arrayOf("string", ExifInterface.TAG_RELATED_SOUND_FILE),
82 | arrayOf("int", ExifInterface.TAG_SATURATION),
83 | arrayOf("int", ExifInterface.TAG_SCENE_CAPTURE_TYPE),
84 | arrayOf("string", ExifInterface.TAG_SCENE_TYPE),
85 | arrayOf("int", ExifInterface.TAG_SENSING_METHOD),
86 | arrayOf("int", ExifInterface.TAG_SHARPNESS),
87 | arrayOf("double", ExifInterface.TAG_SHUTTER_SPEED_VALUE),
88 | arrayOf("string", ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE),
89 | arrayOf("string", ExifInterface.TAG_SPECTRAL_SENSITIVITY),
90 | arrayOf("int", ExifInterface.TAG_SUBFILE_TYPE),
91 | arrayOf("string", ExifInterface.TAG_SUBSEC_TIME),
92 | arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_DIGITIZED),
93 | arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_ORIGINAL),
94 | arrayOf("array", ExifInterface.TAG_SUBJECT_AREA),
95 | arrayOf("double", ExifInterface.TAG_SUBJECT_DISTANCE),
96 | arrayOf("int", ExifInterface.TAG_SUBJECT_DISTANCE_RANGE),
97 | arrayOf("int", ExifInterface.TAG_SUBJECT_LOCATION),
98 | arrayOf("string", ExifInterface.TAG_USER_COMMENT),
99 | arrayOf("int", ExifInterface.TAG_WHITE_BALANCE),
100 | arrayOf("int", ExifInterface.TAG_GPS_ALTITUDE_REF),
101 | arrayOf("string", ExifInterface.TAG_GPS_AREA_INFORMATION),
102 | arrayOf("double", ExifInterface.TAG_GPS_DOP),
103 | arrayOf("string", ExifInterface.TAG_GPS_DATESTAMP),
104 | arrayOf("double", ExifInterface.TAG_GPS_DEST_BEARING),
105 | arrayOf("string", ExifInterface.TAG_GPS_DEST_BEARING_REF),
106 | arrayOf("double", ExifInterface.TAG_GPS_DEST_DISTANCE),
107 | arrayOf("string", ExifInterface.TAG_GPS_DEST_DISTANCE_REF),
108 | arrayOf("double", ExifInterface.TAG_GPS_DEST_LATITUDE),
109 | arrayOf("string", ExifInterface.TAG_GPS_DEST_LATITUDE_REF),
110 | arrayOf("double", ExifInterface.TAG_GPS_DEST_LONGITUDE),
111 | arrayOf("string", ExifInterface.TAG_GPS_DEST_LONGITUDE_REF),
112 | arrayOf("int", ExifInterface.TAG_GPS_DIFFERENTIAL),
113 | arrayOf("string", ExifInterface.TAG_GPS_H_POSITIONING_ERROR),
114 | arrayOf("double", ExifInterface.TAG_GPS_IMG_DIRECTION),
115 | arrayOf("string", ExifInterface.TAG_GPS_IMG_DIRECTION_REF),
116 | arrayOf("string", ExifInterface.TAG_GPS_LATITUDE_REF),
117 | arrayOf("string", ExifInterface.TAG_GPS_LONGITUDE_REF),
118 | arrayOf("string", ExifInterface.TAG_GPS_MAP_DATUM),
119 | arrayOf("string", ExifInterface.TAG_GPS_MEASURE_MODE),
120 | arrayOf("string", ExifInterface.TAG_GPS_PROCESSING_METHOD),
121 | arrayOf("string", ExifInterface.TAG_GPS_SATELLITES),
122 | arrayOf("double", ExifInterface.TAG_GPS_SPEED),
123 | arrayOf("string", ExifInterface.TAG_GPS_SPEED_REF),
124 | arrayOf("string", ExifInterface.TAG_GPS_STATUS),
125 | arrayOf("string", ExifInterface.TAG_GPS_TIMESTAMP),
126 | arrayOf("double", ExifInterface.TAG_GPS_TRACK),
127 | arrayOf("string", ExifInterface.TAG_GPS_TRACK_REF),
128 | arrayOf("string", ExifInterface.TAG_GPS_VERSION_ID),
129 | arrayOf("string", ExifInterface.TAG_INTEROPERABILITY_INDEX),
130 | arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH),
131 | arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH),
132 | arrayOf("int", ExifInterface.TAG_DNG_VERSION),
133 | arrayOf("int", ExifInterface.TAG_DEFAULT_CROP_SIZE),
134 | arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_START),
135 | arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH),
136 | arrayOf("int", ExifInterface.TAG_ORF_ASPECT_FRAME),
137 | arrayOf("int", ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER),
138 | arrayOf("int", ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER),
139 | arrayOf("int", ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER),
140 | arrayOf("int", ExifInterface.TAG_RW2_SENSOR_TOP_BORDER),
141 | arrayOf("int", ExifInterface.TAG_RW2_ISO)
142 | )
143 |
--------------------------------------------------------------------------------