@capacitor-mlkit/selfie-segmentation 5.2.0

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 (33) hide show
  1. package/CapacitorMlkitSelfieSegmentation.podspec +19 -0
  2. package/LICENSE +201 -0
  3. package/README.md +112 -0
  4. package/android/build.gradle +60 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/io/capawesome/capacitorjs/plugins/mlkit/selfiesegmentation/ProcessImageResultCallback.java +11 -0
  7. package/android/src/main/java/io/capawesome/capacitorjs/plugins/mlkit/selfiesegmentation/SelfieSegmentation.java +132 -0
  8. package/android/src/main/java/io/capawesome/capacitorjs/plugins/mlkit/selfiesegmentation/SelfieSegmentationPlugin.java +88 -0
  9. package/android/src/main/java/io/capawesome/capacitorjs/plugins/mlkit/selfiesegmentation/classes/ProcessImageOptions.java +47 -0
  10. package/android/src/main/java/io/capawesome/capacitorjs/plugins/mlkit/selfiesegmentation/classes/ProcessImageResult.java +29 -0
  11. package/android/src/main/res/.gitkeep +0 -0
  12. package/dist/docs.json +156 -0
  13. package/dist/esm/definitions.d.ts +65 -0
  14. package/dist/esm/definitions.js +2 -0
  15. package/dist/esm/definitions.js.map +1 -0
  16. package/dist/esm/index.d.ts +4 -0
  17. package/dist/esm/index.js +7 -0
  18. package/dist/esm/index.js.map +1 -0
  19. package/dist/esm/web.d.ts +6 -0
  20. package/dist/esm/web.js +10 -0
  21. package/dist/esm/web.js.map +1 -0
  22. package/dist/plugin.cjs.js +26 -0
  23. package/dist/plugin.cjs.js.map +1 -0
  24. package/dist/plugin.js +29 -0
  25. package/dist/plugin.js.map +1 -0
  26. package/ios/Plugin/Classes/ProcessImageOptions.swift +64 -0
  27. package/ios/Plugin/Classes/ProcessImageResult.swift +30 -0
  28. package/ios/Plugin/Info.plist +24 -0
  29. package/ios/Plugin/SelfieSegmentation.swift +199 -0
  30. package/ios/Plugin/SelfieSegmentationPlugin.h +10 -0
  31. package/ios/Plugin/SelfieSegmentationPlugin.m +8 -0
  32. package/ios/Plugin/SelfieSegmentationPlugin.swift +61 -0
  33. package/package.json +91 -0
@@ -0,0 +1,19 @@
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 = 'CapacitorMlkitSelfieSegmentation'
7
+ s.version = package['version']
8
+ s.summary = package['description']
9
+ s.license = package['license']
10
+ s.homepage = package['repository']['url']
11
+ s.author = package['author']
12
+ s.source = { :git => package['repository']['url'], :tag => s.version.to_s }
13
+ s.source_files = 'ios/Plugin/**/*.{swift,h,m,c,cc,mm,cpp}'
14
+ s.ios.deployment_target = '13.0'
15
+ s.dependency 'Capacitor'
16
+ s.dependency 'GoogleMLKit/SegmentationSelfie', '4.0.0'
17
+ s.swift_version = '5.1'
18
+ s.static_framework = true
19
+ end
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Robin Genz
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # @capacitor-mlkit/selfie-segmentation
2
+
3
+ Unofficial Capacitor plugin for [ML Kit Selfie Segmentation](https://developers.google.com/ml-kit/vision/selfie-segmentation).[^1]
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @capacitor-mlkit/selfie-segmentation
9
+ npx cap sync
10
+ ```
11
+
12
+ #### Variables
13
+
14
+ This plugin will use the following project variables (defined in your app’s `variables.gradle` file):
15
+
16
+ - `$mlkitSelfieSegmentationVersion` version of `com.google.mlkit:segmentation-selfie` (default: `16.0.0-beta4`)
17
+
18
+ ## Configuration
19
+
20
+ No configuration required for this plugin.
21
+
22
+ ## Demo
23
+
24
+ A working example can be found here: [robingenz/capacitor-mlkit-plugin-demo](https://github.com/robingenz/capacitor-mlkit-plugin-demo)
25
+
26
+ ## Usage
27
+
28
+ ```typescript
29
+ import { SelfieSegmentation } from '@capacitor-mlkit/selfie-segmentation';
30
+
31
+ const processImage = async () => {
32
+ const { path } = await SelfieSegmentation.processImage({
33
+ path: 'path/to/image.jpg',
34
+ confidence: 0.7,
35
+ });
36
+ return path;
37
+ };
38
+ ```
39
+
40
+ ## API
41
+
42
+ <docgen-index>
43
+
44
+ * [`processImage(...)`](#processimage)
45
+ * [Interfaces](#interfaces)
46
+
47
+ </docgen-index>
48
+
49
+ <docgen-api>
50
+ <!--Update the source file JSDoc comments and rerun docgen to update the docs below-->
51
+
52
+ ### processImage(...)
53
+
54
+ ```typescript
55
+ processImage(options: ProcessImageOptions) => Promise<ProcessImageResult>
56
+ ```
57
+
58
+ Performs segmentation on an input image.
59
+
60
+ Only available on Android and iOS.
61
+
62
+ | Param | Type |
63
+ | ------------- | ------------------------------------------------------------------- |
64
+ | **`options`** | <code><a href="#processimageoptions">ProcessImageOptions</a></code> |
65
+
66
+ **Returns:** <code>Promise&lt;<a href="#processimageresult">ProcessImageResult</a>&gt;</code>
67
+
68
+ **Since:** 5.2.0
69
+
70
+ --------------------
71
+
72
+
73
+ ### Interfaces
74
+
75
+
76
+ #### ProcessImageResult
77
+
78
+ | Prop | Type | Description | Since |
79
+ | ------------ | ------------------- | ------------------------------------- | ----- |
80
+ | **`path`** | <code>string</code> | The path to the segmented image file. | 5.2.0 |
81
+ | **`width`** | <code>number</code> | Returns the width of the image file. | 5.2.0 |
82
+ | **`height`** | <code>number</code> | Returns the height of the image file. | 5.2.0 |
83
+
84
+
85
+ #### ProcessImageOptions
86
+
87
+ | Prop | Type | Description | Default | Since |
88
+ | ---------------- | ------------------- | ----------------------------------------------------------------------------------------- | ---------------- | ----- |
89
+ | **`path`** | <code>string</code> | The local path to the image file. | | 5.2.0 |
90
+ | **`width`** | <code>number</code> | Scale the image to this width. If no `height` is given, it will respect the aspect ratio. | | 5.2.0 |
91
+ | **`height`** | <code>number</code> | Scale the image to this height. If no `width` is given, it will respect the aspect ratio. | | 5.2.0 |
92
+ | **`confidence`** | <code>number</code> | Sets the confidence threshold. | <code>0.9</code> | 5.2.0 |
93
+
94
+ </docgen-api>
95
+
96
+ ## Terms & Privacy
97
+
98
+ This plugin uses the [Google ML Kit](https://developers.google.com/ml-kit):
99
+
100
+ - [Terms & Privacy](https://developers.google.com/ml-kit/terms)
101
+ - [Android Data Disclosure](https://developers.google.com/ml-kit/android-data-disclosure)
102
+ - [iOS Data Disclosure](https://developers.google.com/ml-kit/ios-data-disclosure)
103
+
104
+ ## Changelog
105
+
106
+ See [CHANGELOG.md](https://github.com/capawesome-team/capacitor-mlkit/blob/main/packages/selfie-segmentation/CHANGELOG.md).
107
+
108
+ ## License
109
+
110
+ See [LICENSE](https://github.com/capawesome-team/capacitor-mlkit/blob/main/packages/selfie-segmentation/LICENSE).
111
+
112
+ [^1]: This project is not affiliated with, endorsed by, sponsored by, or approved by Google LLC or any of their affiliates or subsidiaries.
@@ -0,0 +1,60 @@
1
+ ext {
2
+ junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
3
+ androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.6.1'
4
+ androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.1.5'
5
+ androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.5.1'
6
+ mlkitSelfieSegmentationVersion = project.hasProperty('mlkitSelfieSegmentationVersion') ? rootProject.ext.mlkitSelfieSegmentationVersion : '16.0.0-beta4'
7
+ }
8
+
9
+ buildscript {
10
+ repositories {
11
+ google()
12
+ mavenCentral()
13
+ }
14
+ dependencies {
15
+ classpath 'com.android.tools.build:gradle:8.0.0'
16
+ }
17
+ }
18
+
19
+ apply plugin: 'com.android.library'
20
+
21
+ android {
22
+ namespace "io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation"
23
+ compileSdkVersion project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 33
24
+ defaultConfig {
25
+ minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22
26
+ targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 33
27
+ versionCode 1
28
+ versionName "1.0"
29
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
30
+ }
31
+ buildTypes {
32
+ release {
33
+ minifyEnabled false
34
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
35
+ }
36
+ }
37
+ lintOptions {
38
+ abortOnError false
39
+ }
40
+ compileOptions {
41
+ sourceCompatibility JavaVersion.VERSION_17
42
+ targetCompatibility JavaVersion.VERSION_17
43
+ }
44
+ }
45
+
46
+ repositories {
47
+ google()
48
+ mavenCentral()
49
+ }
50
+
51
+
52
+ dependencies {
53
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
54
+ implementation project(':capacitor-android')
55
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
56
+ implementation "com.google.mlkit:segmentation-selfie:$mlkitSelfieSegmentationVersion"
57
+ testImplementation "junit:junit:$junitVersion"
58
+ androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
59
+ androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
60
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,11 @@
1
+ package io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation;
2
+
3
+ import io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation.classes.ProcessImageResult;
4
+
5
+ public interface ProcessImageResultCallback {
6
+ void success(ProcessImageResult result);
7
+
8
+ void cancel();
9
+
10
+ void error(Exception exception);
11
+ }
@@ -0,0 +1,132 @@
1
+ package io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation;
2
+
3
+ import android.annotation.SuppressLint;
4
+ import android.graphics.Bitmap;
5
+ import android.net.Uri;
6
+ import androidx.annotation.NonNull;
7
+ import androidx.annotation.Nullable;
8
+ import com.google.mlkit.vision.common.InputImage;
9
+ import com.google.mlkit.vision.segmentation.Segmentation;
10
+ import com.google.mlkit.vision.segmentation.Segmenter;
11
+ import com.google.mlkit.vision.segmentation.selfie.SelfieSegmenterOptions;
12
+ import io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation.classes.ProcessImageOptions;
13
+ import io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation.classes.ProcessImageResult;
14
+ import java.io.File;
15
+ import java.io.FileOutputStream;
16
+ import java.io.OutputStream;
17
+ import java.nio.ByteBuffer;
18
+ import java.nio.ByteOrder;
19
+ import java.text.SimpleDateFormat;
20
+ import java.util.Date;
21
+ import java.util.Objects;
22
+
23
+ public class SelfieSegmentation {
24
+
25
+ @NonNull
26
+ private final SelfieSegmentationPlugin plugin;
27
+
28
+ public SelfieSegmentation(@NonNull SelfieSegmentationPlugin plugin) {
29
+ this.plugin = plugin;
30
+ }
31
+
32
+ @Nullable
33
+ public InputImage createInputImageFromFilePath(@NonNull String path) {
34
+ try {
35
+ return InputImage.fromFilePath(this.plugin.getContext(), Uri.parse(path));
36
+ } catch (Exception exception) {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ public void processImage(ProcessImageOptions options, ProcessImageResultCallback callback) {
42
+ InputImage inputImage = options.getInputImage();
43
+ Float threshold = options.getConfidence();
44
+
45
+ SelfieSegmenterOptions.Builder builder = new SelfieSegmenterOptions.Builder();
46
+ builder.setDetectorMode(SelfieSegmenterOptions.SINGLE_IMAGE_MODE);
47
+ SelfieSegmenterOptions selfieSegmenterOptions = builder.build();
48
+
49
+ final Segmenter segmenter = Segmentation.getClient(selfieSegmenterOptions);
50
+
51
+ plugin
52
+ .getActivity()
53
+ .runOnUiThread(
54
+ () ->
55
+ segmenter
56
+ .process(inputImage)
57
+ .addOnSuccessListener(
58
+ segmentationMask -> {
59
+ segmenter.close();
60
+
61
+ ByteBuffer mask = segmentationMask.getBuffer();
62
+
63
+ Bitmap bitmap = inputImage.getBitmapInternal();
64
+ Objects.requireNonNull(bitmap).setHasAlpha(true);
65
+
66
+ ByteBuffer pixels = ByteBuffer.allocateDirect(bitmap.getAllocationByteCount());
67
+ bitmap.copyPixelsToBuffer(pixels);
68
+
69
+ final boolean bigEndian = pixels.order() == ByteOrder.BIG_ENDIAN;
70
+ final int ALPHA = bigEndian ? 3 : 0;
71
+ final int RED = bigEndian ? 2 : 1;
72
+ final int GREEN = bigEndian ? 1 : 2;
73
+ final int BLUE = bigEndian ? 0 : 3;
74
+
75
+ for (int i = 0; i < pixels.capacity() >> 2; i++) {
76
+ float confidence = mask.getFloat();
77
+
78
+ if (confidence >= threshold) {
79
+ byte red = pixels.get((i << 2) + RED);
80
+ byte green = pixels.get((i << 2) + GREEN);
81
+ byte blue = pixels.get((i << 2) + BLUE);
82
+
83
+ pixels.put((i << 2) + ALPHA, (byte) (0xff));
84
+ pixels.put((i << 2) + RED, (byte) (red * confidence));
85
+ pixels.put((i << 2) + GREEN, (byte) (green * confidence));
86
+ pixels.put((i << 2) + BLUE, (byte) (blue * confidence));
87
+ } else {
88
+ pixels.putInt(i << 2, 0x00000000); // transparent
89
+ }
90
+ }
91
+
92
+ bitmap.copyPixelsFromBuffer(pixels.rewind());
93
+
94
+ // Create an image file name
95
+ @SuppressLint("SimpleDateFormat")
96
+ String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
97
+ String imageFileName = "PNG_" + timeStamp + "_";
98
+
99
+ try {
100
+ File image = File.createTempFile(imageFileName, ".png");
101
+
102
+ OutputStream stream = new FileOutputStream(image);
103
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
104
+ stream.close();
105
+
106
+ ProcessImageResult result = new ProcessImageResult(
107
+ image.getAbsolutePath(),
108
+ bitmap.getWidth(),
109
+ bitmap.getHeight()
110
+ );
111
+
112
+ callback.success(result);
113
+ } catch (Exception exception) {
114
+ callback.error(exception);
115
+ }
116
+ }
117
+ )
118
+ .addOnCanceledListener(
119
+ () -> {
120
+ segmenter.close();
121
+ callback.cancel();
122
+ }
123
+ )
124
+ .addOnFailureListener(
125
+ exception -> {
126
+ segmenter.close();
127
+ callback.error(exception);
128
+ }
129
+ )
130
+ );
131
+ }
132
+ }
@@ -0,0 +1,88 @@
1
+ package io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation;
2
+
3
+ import com.getcapacitor.Logger;
4
+ import com.getcapacitor.Plugin;
5
+ import com.getcapacitor.PluginCall;
6
+ import com.getcapacitor.PluginMethod;
7
+ import com.getcapacitor.annotation.CapacitorPlugin;
8
+ import com.google.mlkit.vision.common.InputImage;
9
+ import io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation.classes.ProcessImageOptions;
10
+ import io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation.classes.ProcessImageResult;
11
+
12
+ @CapacitorPlugin(name = "SelfieSegmentation")
13
+ public class SelfieSegmentationPlugin extends Plugin {
14
+
15
+ public static final String TAG = "SelfieSegmentation";
16
+
17
+ public static final String ERROR_PROCESS_IMAGE_CANCELED = "processImage canceled.";
18
+ public static final String ERROR_PATH_MISSING = "path must be provided.";
19
+ public static final String ERROR_LOAD_IMAGE_FAILED = "The image could not be loaded.";
20
+
21
+ public static final float CONFIDENCE = 0.9f;
22
+
23
+ private SelfieSegmentation implementation;
24
+
25
+ @Override
26
+ public void load() {
27
+ try {
28
+ implementation = new SelfieSegmentation(this);
29
+ } catch (Exception exception) {
30
+ Logger.error(TAG, exception.getMessage(), exception);
31
+ }
32
+ }
33
+
34
+ @PluginMethod
35
+ public void processImage(PluginCall call) {
36
+ try {
37
+ String path = call.getString("path", null);
38
+ if (path == null) {
39
+ call.reject(ERROR_PATH_MISSING);
40
+ return;
41
+ }
42
+
43
+ Integer width = call.getInt("width", null);
44
+ Integer height = call.getInt("height", null);
45
+
46
+ Float confidence = call.getFloat("confidence", CONFIDENCE);
47
+
48
+ InputImage image = implementation.createInputImageFromFilePath(path);
49
+ if (image == null) {
50
+ call.reject(ERROR_LOAD_IMAGE_FAILED);
51
+ return;
52
+ }
53
+ ProcessImageOptions options = new ProcessImageOptions(image, width, height, confidence);
54
+
55
+ implementation.processImage(
56
+ options,
57
+ new ProcessImageResultCallback() {
58
+ @Override
59
+ public void success(ProcessImageResult result) {
60
+ try {
61
+ call.resolve(result.toJSObject());
62
+ } catch (Exception exception) {
63
+ String message = exception.getMessage();
64
+ Logger.error(TAG, message, exception);
65
+ call.reject(message);
66
+ }
67
+ }
68
+
69
+ @Override
70
+ public void cancel() {
71
+ call.reject(ERROR_PROCESS_IMAGE_CANCELED);
72
+ }
73
+
74
+ @Override
75
+ public void error(Exception exception) {
76
+ String message = exception.getMessage();
77
+ Logger.error(TAG, message, exception);
78
+ call.reject(message);
79
+ }
80
+ }
81
+ );
82
+ } catch (Exception exception) {
83
+ String message = exception.getMessage();
84
+ Logger.error(TAG, message, exception);
85
+ call.reject(message);
86
+ }
87
+ }
88
+ }
@@ -0,0 +1,47 @@
1
+ package io.capawesome.capacitorjs.plugins.mlkit.selfiesegmentation.classes;
2
+
3
+ import android.graphics.Bitmap;
4
+ import com.google.mlkit.vision.common.InputImage;
5
+ import java.util.Objects;
6
+
7
+ public class ProcessImageOptions {
8
+
9
+ private final InputImage inputImage;
10
+
11
+ private final Float confidence;
12
+
13
+ public ProcessImageOptions(InputImage inputImage, Integer width, Integer height, Float confidence) {
14
+ this.inputImage = scaledImage(inputImage, width, height);
15
+
16
+ this.confidence = confidence;
17
+ }
18
+
19
+ public InputImage getInputImage() {
20
+ return inputImage;
21
+ }
22
+
23
+ public Float getConfidence() {
24
+ return confidence;
25
+ }
26
+
27
+ private InputImage scaledImage(InputImage inputImage, Integer width, Integer height) {
28
+ float scaleX = (width != null) ? width * 1f / inputImage.getWidth() : 0f;
29
+ float scaleY = (height != null) ? height * 1f / inputImage.getHeight() : 0f;
30
+
31
+ if (scaleX > 0f || scaleY > 0f) {
32
+ if (scaleX > 0f && scaleY == 0f) scaleY = scaleX; else if (scaleY > 0f && scaleX == 0f) scaleX = scaleY;
33
+
34
+ return InputImage.fromBitmap(
35
+ Bitmap.createScaledBitmap(
36
+ Objects.requireNonNull(inputImage.getBitmapInternal()),
37
+ (int) (inputImage.getWidth() * scaleX),
38
+ (int) (inputImage.getHeight() * scaleY),
39
+ false
40
+ ),
41
+ inputImage.getRotationDegrees()
42
+ );
43
+ }
44
+
45
+ return inputImage;
46
+ }
47
+ }