capacitor-plugin-camera-forked 2.0.8

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.
@@ -0,0 +1,210 @@
1
+ package com.tonyxlh.capacitor.camera;
2
+
3
+ /*
4
+ * Copyright 2020 Google LLC. All rights reserved.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+
20
+ import android.annotation.TargetApi;
21
+ import android.graphics.Bitmap;
22
+ import android.graphics.BitmapFactory;
23
+ import android.graphics.ImageFormat;
24
+ import android.graphics.Matrix;
25
+ import android.graphics.Rect;
26
+ import android.graphics.YuvImage;
27
+ import android.media.Image;
28
+ import android.media.Image.Plane;
29
+ import android.os.Build.VERSION_CODES;
30
+ import androidx.annotation.Nullable;
31
+ import android.util.Log;
32
+ import androidx.annotation.RequiresApi;
33
+ import androidx.camera.core.ExperimentalGetImage;
34
+ import androidx.camera.core.ImageProxy;
35
+ import java.io.ByteArrayOutputStream;
36
+ import java.nio.ByteBuffer;
37
+
38
+ /** Utils functions for bitmap conversions. */
39
+ public class BitmapUtils {
40
+ private static final String TAG = "BitmapUtils";
41
+
42
+ /** Converts NV21 format byte buffer to bitmap. */
43
+ @Nullable
44
+ public static Bitmap getBitmap(ByteBuffer data, FrameMetadata metadata) {
45
+ data.rewind();
46
+ byte[] imageInBuffer = new byte[data.limit()];
47
+ data.get(imageInBuffer, 0, imageInBuffer.length);
48
+ try {
49
+ YuvImage image =
50
+ new YuvImage(
51
+ imageInBuffer, ImageFormat.NV21, metadata.getWidth(), metadata.getHeight(), null);
52
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
53
+ image.compressToJpeg(new Rect(0, 0, metadata.getWidth(), metadata.getHeight()), 80, stream);
54
+
55
+ Bitmap bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
56
+
57
+ stream.close();
58
+ return rotateBitmap(bmp, metadata.getRotation(), false, false);
59
+ } catch (Exception e) {
60
+ Log.e("VisionProcessorBase", "Error: " + e.getMessage());
61
+ }
62
+ return null;
63
+ }
64
+
65
+ /** Converts a YUV_420_888 image from CameraX API to a bitmap. */
66
+ @RequiresApi(VERSION_CODES.LOLLIPOP)
67
+ @Nullable
68
+ @ExperimentalGetImage
69
+ public static Bitmap getBitmap(ImageProxy image) {
70
+ FrameMetadata frameMetadata =
71
+ new FrameMetadata.Builder()
72
+ .setWidth(image.getWidth())
73
+ .setHeight(image.getHeight())
74
+ .setRotation(image.getImageInfo().getRotationDegrees())
75
+ .build();
76
+
77
+ ByteBuffer nv21Buffer =
78
+ yuv420ThreePlanesToNV21(image.getImage().getPlanes(), image.getWidth(), image.getHeight());
79
+ return getBitmap(nv21Buffer, frameMetadata);
80
+ }
81
+
82
+ /** Rotates a bitmap if it is converted from a bytebuffer. */
83
+ private static Bitmap rotateBitmap(
84
+ Bitmap bitmap, int rotationDegrees, boolean flipX, boolean flipY) {
85
+ Matrix matrix = new Matrix();
86
+
87
+ // Rotate the image back to straight.
88
+ matrix.postRotate(rotationDegrees);
89
+
90
+ // Mirror the image along the X or Y axis.
91
+ matrix.postScale(flipX ? -1.0f : 1.0f, flipY ? -1.0f : 1.0f);
92
+ Bitmap rotatedBitmap =
93
+ Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
94
+
95
+ // Recycle the old bitmap if it has changed.
96
+ if (rotatedBitmap != bitmap) {
97
+ bitmap.recycle();
98
+ }
99
+ return rotatedBitmap;
100
+ }
101
+
102
+ /**
103
+ * Converts YUV_420_888 to NV21 bytebuffer.
104
+ *
105
+ * <p>The NV21 format consists of a single byte array containing the Y, U and V values. For an
106
+ * image of size S, the first S positions of the array contain all the Y values. The remaining
107
+ * positions contain interleaved V and U values. U and V are subsampled by a factor of 2 in both
108
+ * dimensions, so there are S/4 U values and S/4 V values. In summary, the NV21 array will contain
109
+ * S Y values followed by S/4 VU values: YYYYYYYYYYYYYY(...)YVUVUVUVU(...)VU
110
+ *
111
+ * <p>YUV_420_888 is a generic format that can describe any YUV image where U and V are subsampled
112
+ * by a factor of 2 in both dimensions. {@link Image#getPlanes} returns an array with the Y, U and
113
+ * V planes. The Y plane is guaranteed not to be interleaved, so we can just copy its values into
114
+ * the first part of the NV21 array. The U and V planes may already have the representation in the
115
+ * NV21 format. This happens if the planes share the same buffer, the V buffer is one position
116
+ * before the U buffer and the planes have a pixelStride of 2. If this is case, we can just copy
117
+ * them to the NV21 array.
118
+ */
119
+ @RequiresApi(VERSION_CODES.KITKAT)
120
+ private static ByteBuffer yuv420ThreePlanesToNV21(
121
+ Plane[] yuv420888planes, int width, int height) {
122
+ int imageSize = width * height;
123
+ byte[] out = new byte[imageSize + 2 * (imageSize / 4)];
124
+
125
+ if (areUVPlanesNV21(yuv420888planes, width, height)) {
126
+ // Copy the Y values.
127
+ yuv420888planes[0].getBuffer().get(out, 0, imageSize);
128
+
129
+ ByteBuffer uBuffer = yuv420888planes[1].getBuffer();
130
+ ByteBuffer vBuffer = yuv420888planes[2].getBuffer();
131
+ // Get the first V value from the V buffer, since the U buffer does not contain it.
132
+ vBuffer.get(out, imageSize, 1);
133
+ // Copy the first U value and the remaining VU values from the U buffer.
134
+ uBuffer.get(out, imageSize + 1, 2 * imageSize / 4 - 1);
135
+ } else {
136
+ // Fallback to copying the UV values one by one, which is slower but also works.
137
+ // Unpack Y.
138
+ unpackPlane(yuv420888planes[0], width, height, out, 0, 1);
139
+ // Unpack U.
140
+ unpackPlane(yuv420888planes[1], width, height, out, imageSize + 1, 2);
141
+ // Unpack V.
142
+ unpackPlane(yuv420888planes[2], width, height, out, imageSize, 2);
143
+ }
144
+
145
+ return ByteBuffer.wrap(out);
146
+ }
147
+
148
+ /** Checks if the UV plane buffers of a YUV_420_888 image are in the NV21 format. */
149
+ @RequiresApi(VERSION_CODES.KITKAT)
150
+ private static boolean areUVPlanesNV21(Plane[] planes, int width, int height) {
151
+ int imageSize = width * height;
152
+
153
+ ByteBuffer uBuffer = planes[1].getBuffer();
154
+ ByteBuffer vBuffer = planes[2].getBuffer();
155
+
156
+ // Backup buffer properties.
157
+ int vBufferPosition = vBuffer.position();
158
+ int uBufferLimit = uBuffer.limit();
159
+
160
+ // Advance the V buffer by 1 byte, since the U buffer will not contain the first V value.
161
+ vBuffer.position(vBufferPosition + 1);
162
+ // Chop off the last byte of the U buffer, since the V buffer will not contain the last U value.
163
+ uBuffer.limit(uBufferLimit - 1);
164
+
165
+ // Check that the buffers are equal and have the expected number of elements.
166
+ boolean areNV21 =
167
+ (vBuffer.remaining() == (2 * imageSize / 4 - 2)) && (vBuffer.compareTo(uBuffer) == 0);
168
+
169
+ // Restore buffers to their initial state.
170
+ vBuffer.position(vBufferPosition);
171
+ uBuffer.limit(uBufferLimit);
172
+
173
+ return areNV21;
174
+ }
175
+
176
+ /**
177
+ * Unpack an image plane into a byte array.
178
+ *
179
+ * <p>The input plane data will be copied in 'out', starting at 'offset' and every pixel will be
180
+ * spaced by 'pixelStride'. Note that there is no row padding on the output.
181
+ */
182
+ @TargetApi(VERSION_CODES.KITKAT)
183
+ private static void unpackPlane(
184
+ Plane plane, int width, int height, byte[] out, int offset, int pixelStride) {
185
+ ByteBuffer buffer = plane.getBuffer();
186
+ buffer.rewind();
187
+
188
+ // Compute the size of the current plane.
189
+ // We assume that it has the aspect ratio as the original image.
190
+ int numRow = (buffer.limit() + plane.getRowStride() - 1) / plane.getRowStride();
191
+ if (numRow == 0) {
192
+ return;
193
+ }
194
+ int scaleFactor = height / numRow;
195
+ int numCol = width / scaleFactor;
196
+
197
+ // Extract the data in the output buffer.
198
+ int outputPos = offset;
199
+ int rowStart = 0;
200
+ for (int row = 0; row < numRow; row++) {
201
+ int inputPos = rowStart;
202
+ for (int col = 0; col < numCol; col++) {
203
+ out[outputPos] = buffer.get(inputPos);
204
+ outputPos += pixelStride;
205
+ inputPos += plane.getPixelStride();
206
+ }
207
+ rowStart += plane.getRowStride();
208
+ }
209
+ }
210
+ }