react-native-nitro-image-pipeline 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/NitroImagePipeline.podspec +39 -0
  3. package/README.md +125 -0
  4. package/android/CMakeLists.txt +34 -0
  5. package/android/build.gradle +158 -0
  6. package/android/fix-prefab.gradle +51 -0
  7. package/android/gradle.properties +5 -0
  8. package/android/src/main/AndroidManifest.xml +2 -0
  9. package/android/src/main/cpp/cpp-adapter.cpp +9 -0
  10. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/HybridNitroImagePipeline.kt +119 -0
  11. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/NitroImagePipelinePackage.kt +19 -0
  12. package/android/src/main/java/com/margelo/nitro/nitroimagepipeline/transform/BlurTransformation.kt +84 -0
  13. package/ios/Bridge.h +8 -0
  14. package/ios/HybridNitroImagePipeline.swift +114 -0
  15. package/lib/commonjs/index.js +50 -0
  16. package/lib/commonjs/index.js.map +1 -0
  17. package/lib/commonjs/package.json +1 -0
  18. package/lib/commonjs/specs/nitro-image-toolkit.nitro.js +6 -0
  19. package/lib/commonjs/specs/nitro-image-toolkit.nitro.js.map +1 -0
  20. package/lib/module/index.js +45 -0
  21. package/lib/module/index.js.map +1 -0
  22. package/lib/module/specs/nitro-image-toolkit.nitro.js +4 -0
  23. package/lib/module/specs/nitro-image-toolkit.nitro.js.map +1 -0
  24. package/lib/typescript/src/index.d.ts +28 -0
  25. package/lib/typescript/src/index.d.ts.map +1 -0
  26. package/lib/typescript/src/specs/nitro-image-toolkit.nitro.d.ts +20 -0
  27. package/lib/typescript/src/specs/nitro-image-toolkit.nitro.d.ts.map +1 -0
  28. package/nitro.json +24 -0
  29. package/nitrogen/generated/.gitattributes +1 -0
  30. package/nitrogen/generated/android/NitroImagePipeline+autolinking.cmake +81 -0
  31. package/nitrogen/generated/android/NitroImagePipeline+autolinking.gradle +27 -0
  32. package/nitrogen/generated/android/NitroImagePipelineOnLoad.cpp +54 -0
  33. package/nitrogen/generated/android/NitroImagePipelineOnLoad.hpp +34 -0
  34. package/nitrogen/generated/android/c++/JCacheOption.hpp +61 -0
  35. package/nitrogen/generated/android/c++/JHybridNitroImagePipelineSpec.cpp +140 -0
  36. package/nitrogen/generated/android/c++/JHybridNitroImagePipelineSpec.hpp +67 -0
  37. package/nitrogen/generated/android/c++/JOptions.hpp +67 -0
  38. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroimagepipeline/CacheOption.kt +24 -0
  39. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroimagepipeline/HybridNitroImagePipelineSpec.kt +72 -0
  40. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroimagepipeline/NitroImagePipelineOnLoad.kt +35 -0
  41. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroimagepipeline/Options.kt +44 -0
  42. package/nitrogen/generated/ios/NitroImagePipeline+autolinking.rb +60 -0
  43. package/nitrogen/generated/ios/NitroImagePipeline-Swift-Cxx-Bridge.cpp +68 -0
  44. package/nitrogen/generated/ios/NitroImagePipeline-Swift-Cxx-Bridge.hpp +244 -0
  45. package/nitrogen/generated/ios/NitroImagePipeline-Swift-Cxx-Umbrella.hpp +58 -0
  46. package/nitrogen/generated/ios/NitroImagePipelineAutolinking.mm +33 -0
  47. package/nitrogen/generated/ios/NitroImagePipelineAutolinking.swift +26 -0
  48. package/nitrogen/generated/ios/c++/HybridNitroImagePipelineSpecSwift.cpp +11 -0
  49. package/nitrogen/generated/ios/c++/HybridNitroImagePipelineSpecSwift.hpp +124 -0
  50. package/nitrogen/generated/ios/swift/CacheOption.swift +44 -0
  51. package/nitrogen/generated/ios/swift/Func_void.swift +46 -0
  52. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  53. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_margelo__nitro__image__HybridImageSpec_.swift +51 -0
  54. package/nitrogen/generated/ios/swift/HybridNitroImagePipelineSpec.swift +60 -0
  55. package/nitrogen/generated/ios/swift/HybridNitroImagePipelineSpec_cxx.swift +224 -0
  56. package/nitrogen/generated/ios/swift/Options.swift +71 -0
  57. package/nitrogen/generated/shared/c++/CacheOption.hpp +80 -0
  58. package/nitrogen/generated/shared/c++/HybridNitroImagePipelineSpec.cpp +25 -0
  59. package/nitrogen/generated/shared/c++/HybridNitroImagePipelineSpec.hpp +75 -0
  60. package/nitrogen/generated/shared/c++/Options.hpp +93 -0
  61. package/package.json +99 -0
  62. package/src/index.ts +66 -0
  63. package/src/specs/nitro-image-toolkit.nitro.ts +16 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alejandro Paredes Alva
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,39 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "NitroImagePipeline"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported, :visionos => 1.0 }
14
+ s.source = { :git => "https://github.com/aparedes/react-native-nitro-image-pipeline.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = [
17
+ # Implementation (Swift)
18
+ "ios/**/*.{swift}",
19
+ # Autolinking/Registration (Objective-C++)
20
+ "ios/**/*.{m,mm}",
21
+ # Implementation (C++ objects)
22
+ "cpp/**/*.{hpp,cpp}",
23
+ ]
24
+
25
+ load 'nitrogen/generated/ios/NitroImagePipeline+autolinking.rb'
26
+ add_nitrogen_files(s)
27
+
28
+ s.dependency 'React-jsi'
29
+ s.dependency 'React-callinvoker'
30
+ s.dependency 'NitroImage'
31
+
32
+ spm_dependency(s,
33
+ url: 'https://github.com/kean/Nuke',
34
+ requirement: { kind: 'upToNextMajorVersion', minimumVersion: '13.0.0' },
35
+ products: ['Nuke']
36
+ )
37
+
38
+ install_modules_dependencies(s)
39
+ end
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # react-native-nitro-image-pipeline
2
+
3
+ A high-performance image loading, caching, and processing library for React Native, built with [Nitro Modules](https://nitro.margelo.com/).
4
+
5
+ [![Version](https://img.shields.io/npm/v/react-native-nitro-image-pipeline.svg)](https://www.npmjs.com/package/react-native-nitro-image-pipeline)
6
+ [![Downloads](https://img.shields.io/npm/dm/react-native-nitro-image-pipeline.svg)](https://www.npmjs.com/package/react-native-nitro-image-pipeline)
7
+ [![License](https://img.shields.io/npm/l/react-native-nitro-image-pipeline.svg)](https://github.com/aparedes/react-native-nitro-image-pipeline/LICENSE)
8
+
9
+ ## Features
10
+
11
+ - Load remote images with built-in memory and disk caching
12
+ - Prefetch single or multiple images in the background
13
+ - Apply Gaussian blur and rounded corners at load time
14
+ - Apply Gaussian blur to already-loaded images
15
+ - Clear the image cache on demand
16
+ - `useImage` hook for declarative image loading in components
17
+
18
+ ## Requirements
19
+
20
+ - React Native v0.76.0 or higher
21
+ - Node 18.0.0 or higher
22
+
23
+ > [!IMPORTANT]
24
+ > To support `Nitro Views` you need React Native v0.78.0 or higher.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ # npm
30
+ npm install react-native-nitro-image-pipeline react-native-nitro-modules react-native-nitro-image
31
+
32
+ # pnpm
33
+ pnpm add react-native-nitro-image-pipeline react-native-nitro-modules react-native-nitro-image
34
+
35
+ # bun
36
+ bun add react-native-nitro-image-pipeline react-native-nitro-modules react-native-nitro-image
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ ### `useImage` hook
42
+
43
+ The simplest way to load an image in a component:
44
+
45
+ ```tsx
46
+ import { useImage } from 'react-native-nitro-image-pipeline';
47
+
48
+ function MyComponent() {
49
+ const { image, error } = useImage({
50
+ url: 'https://example.com/photo.jpg',
51
+ blur: 4,
52
+ cornerRadius: 12,
53
+ });
54
+
55
+ if (error) return <Text>Failed to load image</Text>;
56
+ if (!image) return <ActivityIndicator />;
57
+
58
+ // use `image` with react-native-nitro-image
59
+ return <NitroImage source={image} />;
60
+ }
61
+ ```
62
+
63
+ ### Direct API
64
+
65
+ ```ts
66
+ import { NitroImagePipeline } from 'react-native-nitro-image-pipeline';
67
+
68
+ // Load an image with options
69
+ const image = await NitroImagePipeline.loadImage('https://example.com/photo.jpg', {
70
+ blur: 4,
71
+ cornerRadius: 12,
72
+ cache: 'disk',
73
+ });
74
+
75
+ // Prefetch a single image
76
+ await NitroImagePipeline.preLoadImage('https://example.com/photo.jpg');
77
+
78
+ // Prefetch multiple images
79
+ await NitroImagePipeline.preLoadImages([
80
+ 'https://example.com/a.jpg',
81
+ 'https://example.com/b.jpg',
82
+ ]);
83
+
84
+ // Apply Gaussian blur to an already-loaded image
85
+ const blurred = await NitroImagePipeline.gaussianBlur(image, 10);
86
+
87
+ // Clear the image cache
88
+ NitroImagePipeline.clearCache();
89
+ ```
90
+
91
+ ## API Reference
92
+
93
+ ### `loadImage(url, options?)`
94
+
95
+ Loads an image from a URL and returns a `Promise<Image>`.
96
+
97
+ | Option | Type | Default | Description |
98
+ |---|---|---|---|
99
+ | `blur` | `number` | `0` | Gaussian blur radius applied at load time |
100
+ | `cornerRadius` | `number` | `0` | Corner radius in points |
101
+ | `cache` | `'memory' \| 'disk' \| 'none'` | platform default | Caching strategy |
102
+
103
+ ### `preLoadImage(url)`
104
+
105
+ Prefetches a single image into the cache. Returns `Promise<void>`.
106
+
107
+ ### `preLoadImages(urls)`
108
+
109
+ Prefetches multiple images into the cache. Returns `Promise<void>`.
110
+
111
+ ### `gaussianBlur(image, radius)`
112
+
113
+ Applies a Gaussian blur to an existing `Image` object. Returns `Promise<Image>`.
114
+
115
+ ### `clearCache()`
116
+
117
+ Removes all cached images from memory and disk.
118
+
119
+ ## Credits
120
+
121
+ Bootstrapped with [create-nitro-module](https://github.com/patrickkabwe/create-nitro-module).
122
+
123
+ ## Contributing
124
+
125
+ Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
@@ -0,0 +1,34 @@
1
+ project(NitroImagePipeline)
2
+ cmake_minimum_required(VERSION 3.9.0)
3
+
4
+ set (PACKAGE_NAME NitroImagePipeline)
5
+ set (CMAKE_VERBOSE_MAKEFILE ON)
6
+ set (CMAKE_CXX_STANDARD 20)
7
+
8
+ # Enable Raw Props parsing in react-native (for Nitro Views)
9
+ add_compile_options(-DRN_SERIALIZABLE_STATE=1)
10
+
11
+ # Define C++ library and add all sources
12
+ add_library(${PACKAGE_NAME} SHARED
13
+ src/main/cpp/cpp-adapter.cpp
14
+ )
15
+
16
+ # Add Nitrogen specs :)
17
+ include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/NitroImagePipeline+autolinking.cmake)
18
+
19
+ # Set up local includes
20
+ include_directories(
21
+ "src/main/cpp"
22
+ "../cpp"
23
+ )
24
+
25
+ find_library(LOG_LIB log)
26
+ find_package(react-native-nitro-image REQUIRED) # <-- for the HybridImage type
27
+
28
+ # Link all libraries together
29
+ target_link_libraries(
30
+ ${PACKAGE_NAME}
31
+ ${LOG_LIB}
32
+ android # <-- Android core
33
+ react-native-nitro-image::NitroImage # <-- NitroImage
34
+ )
@@ -0,0 +1,158 @@
1
+ buildscript {
2
+ repositories {
3
+ google()
4
+ mavenCentral()
5
+ }
6
+
7
+ dependencies {
8
+ classpath "com.android.tools.build:gradle:8.8.0"
9
+ }
10
+ }
11
+
12
+ def reactNativeArchitectures() {
13
+ def value = rootProject.getProperties().get("reactNativeArchitectures")
14
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
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: 'org.jetbrains.kotlin.android'
23
+ apply from: '../nitrogen/generated/android/NitroImagePipeline+autolinking.gradle'
24
+ apply from: "./fix-prefab.gradle"
25
+
26
+ if (isNewArchitectureEnabled()) {
27
+ apply plugin: "com.facebook.react"
28
+ }
29
+
30
+ def getExtOrDefault(name) {
31
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["NitroImagePipeline_" + name]
32
+ }
33
+
34
+ def getExtOrIntegerDefault(name) {
35
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["NitroImagePipeline_" + name]).toInteger()
36
+ }
37
+
38
+ android {
39
+ namespace "com.margelo.nitro.nitroimagepipeline"
40
+
41
+ ndkVersion getExtOrDefault("ndkVersion")
42
+ compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
43
+
44
+ defaultConfig {
45
+ minSdkVersion getExtOrIntegerDefault("minSdkVersion")
46
+ targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
47
+ buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
48
+
49
+ externalNativeBuild {
50
+ cmake {
51
+ cppFlags "-frtti -fexceptions -Wall -Wextra -fstack-protector-all"
52
+ arguments "-DANDROID_STL=c++_shared", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
53
+ abiFilters (*reactNativeArchitectures())
54
+
55
+ buildTypes {
56
+ debug {
57
+ cppFlags "-O1 -g"
58
+ }
59
+ release {
60
+ cppFlags "-O2"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ externalNativeBuild {
68
+ cmake {
69
+ path "CMakeLists.txt"
70
+ }
71
+ }
72
+
73
+ packagingOptions {
74
+ excludes = [
75
+ "META-INF",
76
+ "META-INF/**",
77
+ "**/libc++_shared.so",
78
+ "**/libfbjni.so",
79
+ "**/libjsi.so",
80
+ "**/libfolly_json.so",
81
+ "**/libfolly_runtime.so",
82
+ "**/libglog.so",
83
+ "**/libhermes.so",
84
+ "**/libhermes-executor-debug.so",
85
+ "**/libhermes_executor.so",
86
+ "**/libreactnative.so",
87
+ "**/libreactnativejni.so",
88
+ "**/libturbomodulejsijni.so",
89
+ "**/libreact_nativemodule_core.so",
90
+ "**/libjscexecutor.so"
91
+ ]
92
+ }
93
+
94
+ buildFeatures {
95
+ buildConfig true
96
+ prefab true
97
+ }
98
+
99
+ buildTypes {
100
+ release {
101
+ minifyEnabled false
102
+ }
103
+ }
104
+
105
+ lintOptions {
106
+ disable "GradleCompatible"
107
+ }
108
+
109
+ compileOptions {
110
+ sourceCompatibility JavaVersion.VERSION_1_8
111
+ targetCompatibility JavaVersion.VERSION_1_8
112
+ }
113
+
114
+ sourceSets {
115
+ main {
116
+ if (isNewArchitectureEnabled()) {
117
+ java.srcDirs += [
118
+ // React Codegen files
119
+ "${project.buildDir}/generated/source/codegen/java"
120
+ ]
121
+ }
122
+ }
123
+ }
124
+ }
125
+
126
+ repositories {
127
+ mavenCentral()
128
+ google()
129
+ }
130
+
131
+
132
+ dependencies {
133
+ // For < 0.71, this will be from the local maven repo
134
+ // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
135
+ //noinspection GradleDynamicVersion
136
+ implementation "com.facebook.react:react-native:+"
137
+
138
+ // Add a dependency on NitroModules
139
+ implementation project(":react-native-nitro-modules")
140
+
141
+ // Add a dependency on NitroImage
142
+ implementation project(":react-native-nitro-image")
143
+ // Coil
144
+ implementation("io.coil-kt.coil3:coil:3.3.0")
145
+ implementation("io.coil-kt.coil3:coil-network-okhttp:3.3.0")
146
+ implementation("io.coil-kt.coil3:coil-gif:3.3.0")
147
+ // Cronet (uses Play Services provider — no APK size cost, falls back gracefully if unavailable)
148
+ implementation("com.google.android.gms:play-services-cronet:18.1.0")
149
+ implementation("com.google.net.cronet:cronet-okhttp:0.1.0")
150
+ }
151
+
152
+ if (isNewArchitectureEnabled()) {
153
+ react {
154
+ jsRootDir = file("../src/")
155
+ libraryName = "NitroImagePipeline"
156
+ codegenJavaPackageName = "com.margelo.nitro.nitroimagepipeline"
157
+ }
158
+ }
@@ -0,0 +1,51 @@
1
+ tasks.configureEach { task ->
2
+ // Make sure that we generate our prefab publication file only after having built the native library
3
+ // so that not a header publication file, but a full configuration publication will be generated, which
4
+ // will include the .so file
5
+
6
+ def prefabConfigurePattern = ~/^prefab(.+)ConfigurePackage$/
7
+ def matcher = task.name =~ prefabConfigurePattern
8
+ if (matcher.matches()) {
9
+ def variantName = matcher[0][1]
10
+ task.outputs.upToDateWhen { false }
11
+ task.dependsOn("externalNativeBuild${variantName}")
12
+ }
13
+ }
14
+
15
+ afterEvaluate {
16
+ def abis = reactNativeArchitectures()
17
+ rootProject.allprojects.each { proj ->
18
+ if (proj === rootProject) return
19
+
20
+ def dependsOnThisLib = proj.configurations.findAll { it.canBeResolved }.any { config ->
21
+ config.dependencies.any { dep ->
22
+ dep.group == project.group && dep.name == project.name
23
+ }
24
+ }
25
+ if (!dependsOnThisLib && proj != project) return
26
+
27
+ if (!proj.plugins.hasPlugin('com.android.application') && !proj.plugins.hasPlugin('com.android.library')) {
28
+ return
29
+ }
30
+
31
+ def variants = proj.android.hasProperty('applicationVariants') ? proj.android.applicationVariants : proj.android.libraryVariants
32
+ // Touch the prefab_config.json files to ensure that in ExternalNativeJsonGenerator.kt we will re-trigger the prefab CLI to
33
+ // generate a libnameConfig.cmake file that will contain our native library (.so).
34
+ // See this condition: https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:build-system/gradle-core/src/main/java/com/android/build/gradle/tasks/ExternalNativeJsonGenerator.kt;l=207-219?q=createPrefabBuildSystemGlue
35
+ variants.all { variant ->
36
+ def variantName = variant.name
37
+ abis.each { abi ->
38
+ def searchDir = new File(proj.projectDir, ".cxx/${variantName}")
39
+ if (!searchDir.exists()) return
40
+ def matches = []
41
+ searchDir.eachDir { randomDir ->
42
+ def prefabFile = new File(randomDir, "${abi}/prefab_config.json")
43
+ if (prefabFile.exists()) matches << prefabFile
44
+ }
45
+ matches.each { prefabConfig ->
46
+ prefabConfig.setLastModified(System.currentTimeMillis())
47
+ }
48
+ }
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,5 @@
1
+ NitroImagePipeline_kotlinVersion=2.1.20
2
+ NitroImagePipeline_minSdkVersion=23
3
+ NitroImagePipeline_targetSdkVersion=35
4
+ NitroImagePipeline_compileSdkVersion=34
5
+ NitroImagePipeline_ndkVersion=27.1.12297006
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,9 @@
1
+ #include <jni.h>
2
+ #include <fbjni/fbjni.h>
3
+ #include "NitroImagePipelineOnLoad.hpp"
4
+
5
+ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
6
+ return facebook::jni::initialize(vm, []() {
7
+ margelo::nitro::nitroimagepipeline::registerAllNatives();
8
+ });
9
+ }
@@ -0,0 +1,119 @@
1
+ package com.margelo.nitro.nitroimagepipeline
2
+
3
+ import android.content.Context
4
+ import androidx.core.graphics.drawable.toBitmap
5
+ import coil3.BitmapImage
6
+ import coil3.DrawableImage
7
+ import coil3.ImageLoader
8
+ import coil3.disk.DiskCache
9
+ import coil3.memory.MemoryCache
10
+ import coil3.network.okhttp.OkHttpNetworkFetcherFactory
11
+ import coil3.request.ErrorResult
12
+ import coil3.request.ImageRequest
13
+ import coil3.request.SuccessResult
14
+ import coil3.request.allowHardware
15
+ import coil3.request.transformations
16
+ import coil3.size.Size
17
+ import coil3.transform.RoundedCornersTransformation
18
+ import com.google.net.cronet.okhttptransport.CronetInterceptor
19
+ import com.margelo.nitro.NitroModules
20
+ import com.margelo.nitro.core.Promise
21
+ import com.margelo.nitro.image.HybridImage
22
+ import com.margelo.nitro.image.HybridImageSpec
23
+ import com.margelo.nitro.nitroimagepipeline.transform.BlurTransformation
24
+ import okhttp3.OkHttpClient
25
+ import okio.Path.Companion.toOkioPath
26
+ import org.chromium.net.CronetEngine
27
+
28
+ class HybridNitroImagePipeline : HybridNitroImagePipelineSpec() {
29
+ private val context
30
+ get() = NitroModules.applicationContext as Context
31
+
32
+ private val okHttpClient: OkHttpClient by lazy {
33
+ val builder = OkHttpClient.Builder()
34
+ try {
35
+ val cronetEngine = CronetEngine.Builder(context).build()
36
+ builder.addInterceptor(CronetInterceptor.newBuilder(cronetEngine).build())
37
+ } catch (_: Exception) {
38
+ // Cronet unavailable (no GMS or unsupported device) — use plain OkHttp
39
+ }
40
+ builder.build()
41
+ }
42
+
43
+ private val imageLoader: ImageLoader by lazy {
44
+ ImageLoader.Builder(context)
45
+ .components { add(OkHttpNetworkFetcherFactory(callFactory = okHttpClient)) }
46
+ .memoryCache { MemoryCache.Builder().maxSizePercent(context, 0.25).build() }
47
+ .diskCache {
48
+ DiskCache.Builder()
49
+ .directory(context.cacheDir.resolve("nitro_image_cache").toOkioPath())
50
+ .maxSizeBytes(256L * 1024 * 1024)
51
+ .build()
52
+ }
53
+ .build()
54
+ }
55
+
56
+ override fun loadImage(url: String, options: Options?): Promise<HybridImageSpec> =
57
+ Promise.async {
58
+ val blur = options?.blur?.toFloat() ?: 0f
59
+ val cornerRadius = options?.cornerRadius?.toFloat() ?: 0f
60
+ val transformations = buildList {
61
+ if (blur > 0f) add(BlurTransformation(context, blur))
62
+ if (cornerRadius > 0f) add(RoundedCornersTransformation(cornerRadius))
63
+ }
64
+ val memoryCacheKey = buildString {
65
+ append(url)
66
+ if (blur > 0f) append("_blur$blur")
67
+ if (cornerRadius > 0f) append("_corner$cornerRadius")
68
+ }
69
+ val request =
70
+ ImageRequest.Builder(context)
71
+ .data(url)
72
+ .allowHardware(true)
73
+ .memoryCacheKey(memoryCacheKey)
74
+ .transformations(transformations)
75
+ .build()
76
+
77
+ val result = imageLoader.execute(request)
78
+ when (result) {
79
+ is ErrorResult -> throw result.throwable
80
+ is SuccessResult -> {
81
+ val bitmap =
82
+ when (val img = result.image) {
83
+ is BitmapImage -> img.bitmap
84
+ is DrawableImage -> img.drawable.toBitmap()
85
+ else -> throw Error("Unsupported image type: ${img.javaClass.simpleName}")
86
+ }
87
+ HybridImage(bitmap)
88
+ }
89
+ }
90
+ }
91
+
92
+ override fun preLoadImage(url: String): Promise<Unit> =
93
+ Promise.async {
94
+ val request = ImageRequest.Builder(context).data(url).build()
95
+ imageLoader.execute(request)
96
+ }
97
+
98
+ override fun preLoadImages(urls: Array<String>): Promise<Unit> =
99
+ Promise.async {
100
+ for (url in urls) {
101
+ val request = ImageRequest.Builder(context).data(url).build()
102
+ imageLoader.execute(request)
103
+ }
104
+ }
105
+
106
+ override fun gaussianBlur(image: HybridImageSpec, radius: Double): Promise<HybridImageSpec> =
107
+ Promise.async {
108
+ val hybridImage = image as? HybridImage ?: throw Error("Image is not a HybridImage")
109
+ val clampedRadius = radius.toFloat().coerceIn(0.01f, 25f)
110
+ val blurred =
111
+ BlurTransformation(context, clampedRadius).transform(hybridImage.bitmap, Size.ORIGINAL)
112
+ HybridImage(blurred)
113
+ }
114
+
115
+ override fun clearCache() {
116
+ imageLoader.memoryCache?.clear()
117
+ imageLoader.diskCache?.clear()
118
+ }
119
+ }
@@ -0,0 +1,19 @@
1
+ package com.margelo.nitro.nitroimagepipeline
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfoProvider
7
+
8
+ public class NitroImagePipelinePackage : BaseReactPackage() {
9
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? = null
10
+
11
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider =
12
+ ReactModuleInfoProvider { emptyMap() }
13
+
14
+ companion object {
15
+ init {
16
+ NitroImagePipelineOnLoad.initializeNative();
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,84 @@
1
+ @file:Suppress("DEPRECATION")
2
+
3
+ package com.margelo.nitro.nitroimagepipeline.transform
4
+
5
+ import android.content.Context
6
+ import android.graphics.Bitmap
7
+ import android.graphics.Paint
8
+ import android.renderscript.Allocation
9
+ import android.renderscript.Element
10
+ import android.renderscript.RenderScript
11
+ import android.renderscript.ScriptIntrinsicBlur
12
+ import androidx.core.graphics.applyCanvas
13
+ import androidx.core.graphics.scale
14
+ import coil3.size.Size
15
+ import coil3.transform.Transformation
16
+
17
+ class BlurTransformation(
18
+ private val context: Context,
19
+ private val radius: Float = 10f,
20
+ private val sampling: Float = 1f,
21
+ ) : Transformation() {
22
+
23
+ init {
24
+ require(radius in 0.01..25.0) { "radius must be in (0, 25]." }
25
+ require(sampling >= 1f) { "sampling must be >= 1." }
26
+ }
27
+
28
+ override val cacheKey = "${BlurTransformation::class.java.name}-$radius-$sampling"
29
+
30
+ override suspend fun transform(input: Bitmap, size: Size): Bitmap {
31
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
32
+ // Auto-scale so the blurred image is at most 512px on the longest side.
33
+ // Blur is a low-pass filter so blurring at lower resolution is identical in quality.
34
+ val autoSampling = (maxOf(input.width, input.height) / 512f).coerceAtLeast(sampling)
35
+ val scaledWidth = (input.width / autoSampling).toInt().coerceAtLeast(1)
36
+ val scaledHeight = (input.height / autoSampling).toInt().coerceAtLeast(1)
37
+ val config = input.config ?: Bitmap.Config.ARGB_8888
38
+
39
+ val output = Bitmap.createBitmap(scaledWidth, scaledHeight, config)
40
+ output.applyCanvas {
41
+ scale(1 / autoSampling, 1 / autoSampling)
42
+ drawBitmap(input, 0f, 0f, paint)
43
+ }
44
+
45
+ var script: RenderScript? = null
46
+ var tmpIn: Allocation? = null
47
+ var tmpOut: Allocation? = null
48
+ var blur: ScriptIntrinsicBlur? = null
49
+ try {
50
+ script = RenderScript.create(context)
51
+ tmpIn = Allocation.createFromBitmap(script, output, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT)
52
+ tmpOut = Allocation.createTyped(script, tmpIn.type)
53
+ blur = ScriptIntrinsicBlur.create(script, Element.U8_4(script))
54
+ blur.setRadius(radius)
55
+ blur.setInput(tmpIn)
56
+ blur.forEach(tmpOut)
57
+ tmpOut.copyTo(output)
58
+ } finally {
59
+ script?.destroy()
60
+ tmpIn?.destroy()
61
+ tmpOut?.destroy()
62
+ blur?.destroy()
63
+ }
64
+
65
+ return output.scale(input.width, input.height)
66
+ }
67
+
68
+ override fun equals(other: Any?): Boolean {
69
+ if (this === other) return true
70
+ return other is BlurTransformation &&
71
+ context == other.context &&
72
+ radius == other.radius &&
73
+ sampling == other.sampling
74
+ }
75
+
76
+ override fun hashCode(): Int {
77
+ var result = context.hashCode()
78
+ result = 31 * result + radius.hashCode()
79
+ result = 31 * result + sampling.hashCode()
80
+ return result
81
+ }
82
+
83
+ override fun toString() = "BlurTransformation(radius=$radius, sampling=$sampling)"
84
+ }
package/ios/Bridge.h ADDED
@@ -0,0 +1,8 @@
1
+ //
2
+ // Bridge.h
3
+ // nitro-image-toolkit
4
+ //
5
+ // Created by Alejandro Paredes Alva on 3/31/2026
6
+ //
7
+
8
+ #pragma once