@capgo/camera-preview 3.2.3

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 (51) hide show
  1. package/CapgoCameraPreview.podspec +14 -0
  2. package/LICENSE +21 -0
  3. package/README.md +431 -0
  4. package/android/.project +17 -0
  5. package/android/build.gradle +55 -0
  6. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +6 -0
  8. package/android/gradle.properties +18 -0
  9. package/android/gradlew +160 -0
  10. package/android/gradlew.bat +90 -0
  11. package/android/proguard-rules.pro +21 -0
  12. package/android/settings.gradle +2 -0
  13. package/android/src/androidTest/java/com/getcapacitor/android/ExampleInstrumentedTest.java +26 -0
  14. package/android/src/main/AndroidManifest.xml +5 -0
  15. package/android/src/main/java/com/ahm/capacitor/camera/preview/CameraActivity.java +967 -0
  16. package/android/src/main/java/com/ahm/capacitor/camera/preview/CameraPreview.java +507 -0
  17. package/android/src/main/java/com/ahm/capacitor/camera/preview/CustomSurfaceView.java +23 -0
  18. package/android/src/main/java/com/ahm/capacitor/camera/preview/CustomTextureView.java +29 -0
  19. package/android/src/main/java/com/ahm/capacitor/camera/preview/Preview.java +386 -0
  20. package/android/src/main/java/com/ahm/capacitor/camera/preview/TapGestureDetector.java +24 -0
  21. package/android/src/main/res/layout/bridge_layout_main.xml +15 -0
  22. package/android/src/main/res/layout/camera_activity.xml +68 -0
  23. package/android/src/main/res/values/camera_ids.xml +4 -0
  24. package/android/src/main/res/values/camera_theme.xml +9 -0
  25. package/android/src/main/res/values/colors.xml +3 -0
  26. package/android/src/main/res/values/strings.xml +3 -0
  27. package/android/src/main/res/values/styles.xml +3 -0
  28. package/android/src/test/java/com/getcapacitor/ExampleUnitTest.java +18 -0
  29. package/dist/esm/definitions.d.ts +74 -0
  30. package/dist/esm/definitions.js +2 -0
  31. package/dist/esm/definitions.js.map +1 -0
  32. package/dist/esm/index.d.ts +4 -0
  33. package/dist/esm/index.js +7 -0
  34. package/dist/esm/index.js.map +1 -0
  35. package/dist/esm/web.d.ts +24 -0
  36. package/dist/esm/web.js +135 -0
  37. package/dist/esm/web.js.map +1 -0
  38. package/ios/Plugin/CameraController.swift +647 -0
  39. package/ios/Plugin/Info.plist +24 -0
  40. package/ios/Plugin/Plugin.h +10 -0
  41. package/ios/Plugin/Plugin.m +16 -0
  42. package/ios/Plugin/Plugin.swift +291 -0
  43. package/ios/Plugin.xcodeproj/project.pbxproj +595 -0
  44. package/ios/Plugin.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
  45. package/ios/Plugin.xcworkspace/contents.xcworkspacedata +10 -0
  46. package/ios/Plugin.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +8 -0
  47. package/ios/PluginTests/Info.plist +22 -0
  48. package/ios/PluginTests/PluginTests.swift +35 -0
  49. package/ios/Podfile +13 -0
  50. package/ios/Podfile.lock +23 -0
  51. package/package.json +76 -0
@@ -0,0 +1,967 @@
1
+ package com.ahm.capacitor.camera.preview;
2
+
3
+ import android.app.Activity;
4
+ import android.app.Fragment;
5
+ import android.content.Context;
6
+ import android.content.pm.PackageManager;
7
+ import android.graphics.Bitmap;
8
+ import android.graphics.Bitmap.CompressFormat;
9
+ import android.graphics.BitmapFactory;
10
+ import android.graphics.Canvas;
11
+ import android.graphics.ImageFormat;
12
+ import android.graphics.Matrix;
13
+ import android.graphics.Rect;
14
+ import android.graphics.YuvImage;
15
+ import android.hardware.Camera;
16
+ import android.hardware.Camera.PictureCallback;
17
+ import android.hardware.Camera.ShutterCallback;
18
+ import android.media.AudioManager;
19
+ import android.media.CamcorderProfile;
20
+ import android.media.MediaRecorder;
21
+ import android.os.Bundle;
22
+ import android.util.Base64;
23
+ import android.util.DisplayMetrics;
24
+ import android.util.Log;
25
+ import android.view.GestureDetector;
26
+ import android.view.Gravity;
27
+ import android.view.LayoutInflater;
28
+ import android.view.MotionEvent;
29
+ import android.view.Surface;
30
+ import android.view.Surface;
31
+ import android.view.SurfaceHolder;
32
+ import android.view.SurfaceView;
33
+ import android.view.View;
34
+ import android.view.ViewGroup;
35
+ import android.view.ViewTreeObserver;
36
+ import android.widget.FrameLayout;
37
+ import android.widget.RelativeLayout;
38
+ import androidx.exifinterface.media.ExifInterface;
39
+ import java.io.ByteArrayInputStream;
40
+ import java.io.ByteArrayOutputStream;
41
+ import java.io.File;
42
+ import java.io.FileOutputStream;
43
+ import java.io.IOException;
44
+ import java.util.Arrays;
45
+ import java.util.List;
46
+ import java.util.UUID;
47
+
48
+ public class CameraActivity extends Fragment {
49
+
50
+ public interface CameraPreviewListener {
51
+ void onPictureTaken(String originalPicture);
52
+ void onPictureTakenError(String message);
53
+ void onSnapshotTaken(String originalPicture);
54
+ void onSnapshotTakenError(String message);
55
+ void onFocusSet(int pointX, int pointY);
56
+ void onFocusSetError(String message);
57
+ void onBackButton();
58
+ void onCameraStarted();
59
+ void onStartRecordVideo();
60
+ void onStartRecordVideoError(String message);
61
+ void onStopRecordVideo(String file);
62
+ void onStopRecordVideoError(String error);
63
+ }
64
+
65
+ private CameraPreviewListener eventListener;
66
+ private static final String TAG = "CameraActivity";
67
+ public FrameLayout mainLayout;
68
+ public FrameLayout frameContainerLayout;
69
+
70
+ private Preview mPreview;
71
+ private boolean canTakePicture = true;
72
+
73
+ private View view;
74
+ private Camera.Parameters cameraParameters;
75
+ private Camera mCamera;
76
+ private int numberOfCameras;
77
+ private int cameraCurrentlyLocked;
78
+ private int currentQuality;
79
+
80
+ private enum RecordingState {
81
+ INITIALIZING,
82
+ STARTED,
83
+ STOPPED
84
+ }
85
+
86
+ private RecordingState mRecordingState = RecordingState.INITIALIZING;
87
+ private MediaRecorder mRecorder = null;
88
+ private String recordFilePath;
89
+ private float opacity;
90
+
91
+ // The first rear facing camera
92
+ private int defaultCameraId;
93
+ public String defaultCamera;
94
+ public boolean tapToTakePicture;
95
+ public boolean dragEnabled;
96
+ public boolean tapToFocus;
97
+ public boolean disableExifHeaderStripping;
98
+ public boolean storeToFile;
99
+ public boolean toBack;
100
+ public boolean enableOpacity = false;
101
+ public boolean enableZoom = false;
102
+
103
+ public int width;
104
+ public int height;
105
+ public int x;
106
+ public int y;
107
+
108
+ public void setEventListener(CameraPreviewListener listener) {
109
+ eventListener = listener;
110
+ }
111
+
112
+ private String appResourcesPackage;
113
+
114
+ @Override
115
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
116
+ appResourcesPackage = getActivity().getPackageName();
117
+
118
+ // Inflate the layout for this fragment
119
+ view = inflater.inflate(getResources().getIdentifier("camera_activity", "layout", appResourcesPackage), container, false);
120
+ createCameraPreview();
121
+ return view;
122
+ }
123
+
124
+ public void setRect(int x, int y, int width, int height) {
125
+ this.x = x;
126
+ this.y = y;
127
+ this.width = width;
128
+ this.height = height;
129
+ }
130
+
131
+ private void createCameraPreview() {
132
+ if (mPreview == null) {
133
+ setDefaultCameraId();
134
+
135
+ //set box position and size
136
+ FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
137
+ layoutParams.setMargins(x, y, 0, 0);
138
+ frameContainerLayout =
139
+ (FrameLayout) view.findViewById(getResources().getIdentifier("frame_container", "id", appResourcesPackage));
140
+ frameContainerLayout.setLayoutParams(layoutParams);
141
+
142
+ //video view
143
+ mPreview = new Preview(getActivity(), enableOpacity);
144
+ mainLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("video_view", "id", appResourcesPackage));
145
+ mainLayout.setLayoutParams(
146
+ new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
147
+ );
148
+ mainLayout.addView(mPreview);
149
+ mainLayout.setEnabled(false);
150
+
151
+ if (enableZoom) {
152
+ this.setupTouchAndBackButton();
153
+ }
154
+ }
155
+ }
156
+
157
+ private void setupTouchAndBackButton() {
158
+ final GestureDetector gestureDetector = new GestureDetector(getActivity().getApplicationContext(), new TapGestureDetector());
159
+
160
+ getActivity()
161
+ .runOnUiThread(
162
+ new Runnable() {
163
+ @Override
164
+ public void run() {
165
+ frameContainerLayout.setClickable(true);
166
+ frameContainerLayout.setOnTouchListener(
167
+ new View.OnTouchListener() {
168
+ private int mLastTouchX;
169
+ private int mLastTouchY;
170
+ private int mPosX = 0;
171
+ private int mPosY = 0;
172
+
173
+ @Override
174
+ public boolean onTouch(View v, MotionEvent event) {
175
+ FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) frameContainerLayout.getLayoutParams();
176
+
177
+ boolean isSingleTapTouch = gestureDetector.onTouchEvent(event);
178
+ int action = event.getAction();
179
+ int eventCount = event.getPointerCount();
180
+ Log.d(TAG, "onTouch event, action, count: " + event + ", " + action + ", " + eventCount);
181
+ if (eventCount > 1) {
182
+ // handle multi-touch events
183
+ Camera.Parameters params = mCamera.getParameters();
184
+ if (action == MotionEvent.ACTION_POINTER_DOWN) {
185
+ mDist = getFingerSpacing(event);
186
+ } else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
187
+ handleZoom(event, params);
188
+ }
189
+ } else {
190
+ if (action != MotionEvent.ACTION_MOVE && isSingleTapTouch) {
191
+ if (tapToTakePicture && tapToFocus) {
192
+ setFocusArea(
193
+ (int) event.getX(0),
194
+ (int) event.getY(0),
195
+ new Camera.AutoFocusCallback() {
196
+ public void onAutoFocus(boolean success, Camera camera) {
197
+ if (success) {
198
+ takePicture(0, 0, 85);
199
+ } else {
200
+ Log.d(TAG, "onTouch:" + " setFocusArea() did not suceed");
201
+ }
202
+ }
203
+ }
204
+ );
205
+ } else if (tapToTakePicture) {
206
+ takePicture(0, 0, 85);
207
+ } else if (tapToFocus) {
208
+ setFocusArea(
209
+ (int) event.getX(0),
210
+ (int) event.getY(0),
211
+ new Camera.AutoFocusCallback() {
212
+ public void onAutoFocus(boolean success, Camera camera) {
213
+ if (success) {
214
+ // A callback to JS might make sense here.
215
+ } else {
216
+ Log.d(TAG, "onTouch:" + " setFocusArea() did not suceed");
217
+ }
218
+ }
219
+ }
220
+ );
221
+ }
222
+ return true;
223
+ } else {
224
+ if (dragEnabled) {
225
+ int x;
226
+ int y;
227
+
228
+ switch (event.getAction()) {
229
+ case MotionEvent.ACTION_DOWN:
230
+ if (mLastTouchX == 0 || mLastTouchY == 0) {
231
+ mLastTouchX = (int) event.getRawX() - layoutParams.leftMargin;
232
+ mLastTouchY = (int) event.getRawY() - layoutParams.topMargin;
233
+ } else {
234
+ mLastTouchX = (int) event.getRawX();
235
+ mLastTouchY = (int) event.getRawY();
236
+ }
237
+ break;
238
+ case MotionEvent.ACTION_MOVE:
239
+ x = (int) event.getRawX();
240
+ y = (int) event.getRawY();
241
+
242
+ final float dx = x - mLastTouchX;
243
+ final float dy = y - mLastTouchY;
244
+
245
+ mPosX += dx;
246
+ mPosY += dy;
247
+
248
+ layoutParams.leftMargin = mPosX;
249
+ layoutParams.topMargin = mPosY;
250
+
251
+ frameContainerLayout.setLayoutParams(layoutParams);
252
+
253
+ // Remember this touch position for the next move event
254
+ mLastTouchX = x;
255
+ mLastTouchY = y;
256
+
257
+ break;
258
+ default:
259
+ break;
260
+ }
261
+ }
262
+ }
263
+ }
264
+ return true;
265
+ }
266
+ }
267
+ );
268
+ frameContainerLayout.setFocusableInTouchMode(true);
269
+ frameContainerLayout.requestFocus();
270
+ frameContainerLayout.setOnKeyListener(
271
+ new View.OnKeyListener() {
272
+ @Override
273
+ public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
274
+ if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
275
+ eventListener.onBackButton();
276
+ return true;
277
+ }
278
+ return false;
279
+ }
280
+ }
281
+ );
282
+ }
283
+
284
+ private float mDist = 0F;
285
+
286
+ private void handleZoom(MotionEvent event, Camera.Parameters params) {
287
+ if (mCamera != null) {
288
+ mCamera.cancelAutoFocus();
289
+ int maxZoom = params.getMaxZoom();
290
+ int zoom = params.getZoom();
291
+ float newDist = getFingerSpacing(event);
292
+ if (newDist > mDist) {
293
+ //zoom in
294
+ if (zoom < maxZoom) zoom++;
295
+ } else if (newDist < mDist) {
296
+ //zoom out
297
+ if (zoom > 0) zoom--;
298
+ }
299
+ mDist = newDist;
300
+ params.setZoom(zoom);
301
+ mCamera.setParameters(params);
302
+ }
303
+ }
304
+ }
305
+ );
306
+ }
307
+
308
+ private void setDefaultCameraId() {
309
+ // Find the total number of cameras available
310
+ numberOfCameras = Camera.getNumberOfCameras();
311
+
312
+ int facing = "front".equals(defaultCamera) ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;
313
+
314
+ // Find the ID of the default camera
315
+ Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
316
+ for (int i = 0; i < numberOfCameras; i++) {
317
+ Camera.getCameraInfo(i, cameraInfo);
318
+ if (cameraInfo.facing == facing) {
319
+ defaultCameraId = i;
320
+ break;
321
+ }
322
+ }
323
+ }
324
+
325
+ @Override
326
+ public void onResume() {
327
+ super.onResume();
328
+
329
+ mCamera = Camera.open(defaultCameraId);
330
+
331
+ if (cameraParameters != null) {
332
+ mCamera.setParameters(cameraParameters);
333
+ }
334
+
335
+ cameraCurrentlyLocked = defaultCameraId;
336
+
337
+ if (mPreview.mPreviewSize == null) {
338
+ mPreview.setCamera(mCamera, cameraCurrentlyLocked);
339
+ eventListener.onCameraStarted();
340
+ } else {
341
+ mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
342
+ mCamera.startPreview();
343
+ }
344
+
345
+ Log.d(TAG, "cameraCurrentlyLocked:" + cameraCurrentlyLocked);
346
+
347
+ final FrameLayout frameContainerLayout = (FrameLayout) view.findViewById(
348
+ getResources().getIdentifier("frame_container", "id", appResourcesPackage)
349
+ );
350
+
351
+ ViewTreeObserver viewTreeObserver = frameContainerLayout.getViewTreeObserver();
352
+
353
+ if (viewTreeObserver.isAlive()) {
354
+ viewTreeObserver.addOnGlobalLayoutListener(
355
+ new ViewTreeObserver.OnGlobalLayoutListener() {
356
+ @Override
357
+ public void onGlobalLayout() {
358
+ frameContainerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
359
+ frameContainerLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
360
+ Activity activity = getActivity();
361
+ if (isAdded() && activity != null) {
362
+ final RelativeLayout frameCamContainerLayout = (RelativeLayout) view.findViewById(
363
+ getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage)
364
+ );
365
+
366
+ FrameLayout.LayoutParams camViewLayout = new FrameLayout.LayoutParams(
367
+ frameContainerLayout.getWidth(),
368
+ frameContainerLayout.getHeight()
369
+ );
370
+ camViewLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
371
+ frameCamContainerLayout.setLayoutParams(camViewLayout);
372
+ }
373
+ }
374
+ }
375
+ );
376
+ }
377
+ }
378
+
379
+ @Override
380
+ public void onPause() {
381
+ super.onPause();
382
+
383
+ // Because the Camera object is a shared resource, it's very important to release it when the activity is paused.
384
+ if (mCamera != null) {
385
+ setDefaultCameraId();
386
+ mPreview.setCamera(null, -1);
387
+ mCamera.setPreviewCallback(null);
388
+ mCamera.release();
389
+ mCamera = null;
390
+ }
391
+ }
392
+
393
+ public Camera getCamera() {
394
+ return mCamera;
395
+ }
396
+
397
+ public void switchCamera() {
398
+ // check for availability of multiple cameras
399
+ if (numberOfCameras == 1) {
400
+ //There is only one camera available
401
+ } else {
402
+ Log.d(TAG, "numberOfCameras: " + numberOfCameras);
403
+
404
+ // OK, we have multiple cameras. Release this camera -> cameraCurrentlyLocked
405
+ if (mCamera != null) {
406
+ mCamera.stopPreview();
407
+ mPreview.setCamera(null, -1);
408
+ mCamera.release();
409
+ mCamera = null;
410
+ }
411
+
412
+ Log.d(TAG, "cameraCurrentlyLocked := " + Integer.toString(cameraCurrentlyLocked));
413
+ try {
414
+ cameraCurrentlyLocked = (cameraCurrentlyLocked + 1) % numberOfCameras;
415
+ Log.d(TAG, "cameraCurrentlyLocked new: " + cameraCurrentlyLocked);
416
+ } catch (Exception exception) {
417
+ Log.d(TAG, exception.getMessage());
418
+ }
419
+
420
+ // Acquire the next camera and request Preview to reconfigure parameters.
421
+ mCamera = Camera.open(cameraCurrentlyLocked);
422
+
423
+ if (cameraParameters != null) {
424
+ Log.d(TAG, "camera parameter not null");
425
+
426
+ // Check for flashMode as well to prevent error on frontward facing camera.
427
+ List<String> supportedFlashModesNewCamera = mCamera.getParameters().getSupportedFlashModes();
428
+ String currentFlashModePreviousCamera = cameraParameters.getFlashMode();
429
+ if (supportedFlashModesNewCamera != null && supportedFlashModesNewCamera.contains(currentFlashModePreviousCamera)) {
430
+ Log.d(TAG, "current flash mode supported on new camera. setting params");
431
+ /* mCamera.setParameters(cameraParameters);
432
+ The line above is disabled because parameters that can actually be changed are different from one device to another. Makes less sense trying to reconfigure them when changing camera device while those settings gan be changed using plugin methods.
433
+ */
434
+ } else {
435
+ Log.d(TAG, "current flash mode NOT supported on new camera");
436
+ }
437
+ } else {
438
+ Log.d(TAG, "camera parameter NULL");
439
+ }
440
+
441
+ mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
442
+
443
+ mCamera.startPreview();
444
+ }
445
+ }
446
+
447
+ public void setCameraParameters(Camera.Parameters params) {
448
+ cameraParameters = params;
449
+
450
+ if (mCamera != null && cameraParameters != null) {
451
+ mCamera.setParameters(cameraParameters);
452
+ }
453
+ }
454
+
455
+ public boolean hasFrontCamera() {
456
+ return getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
457
+ }
458
+
459
+ public static Bitmap applyMatrix(Bitmap source, Matrix matrix) {
460
+ return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
461
+ }
462
+
463
+ ShutterCallback shutterCallback = new ShutterCallback() {
464
+ public void onShutter() {
465
+ // do nothing, availabilty of this callback causes default system shutter sound to work
466
+ }
467
+ };
468
+
469
+ private static int exifToDegrees(int exifOrientation) {
470
+ if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
471
+ return 90;
472
+ } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
473
+ return 180;
474
+ } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
475
+ return 270;
476
+ }
477
+ return 0;
478
+ }
479
+
480
+ private String getTempDirectoryPath() {
481
+ File cache = null;
482
+
483
+ // Use internal storage
484
+ cache = getActivity().getCacheDir();
485
+
486
+ // Create the cache directory if it doesn't exist
487
+ cache.mkdirs();
488
+ return cache.getAbsolutePath();
489
+ }
490
+
491
+ private String getTempFilePath() {
492
+ return getTempDirectoryPath() + "/cpcp_capture_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8) + ".jpg";
493
+ }
494
+
495
+ PictureCallback jpegPictureCallback = new PictureCallback() {
496
+ public void onPictureTaken(byte[] data, Camera arg1) {
497
+ Log.d(TAG, "CameraPreview jpegPictureCallback");
498
+
499
+ try {
500
+ if (!disableExifHeaderStripping) {
501
+ Matrix matrix = new Matrix();
502
+ if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT) {
503
+ matrix.preScale(1.0f, -1.0f);
504
+ }
505
+
506
+ ExifInterface exifInterface = new ExifInterface(new ByteArrayInputStream(data));
507
+ int rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
508
+ int rotationInDegrees = exifToDegrees(rotation);
509
+
510
+ if (rotation != 0f) {
511
+ matrix.preRotate(rotationInDegrees);
512
+ }
513
+
514
+ // Check if matrix has changed. In that case, apply matrix and override data
515
+ if (!matrix.isIdentity()) {
516
+ Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
517
+ bitmap = applyMatrix(bitmap, matrix);
518
+
519
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
520
+ bitmap.compress(CompressFormat.JPEG, currentQuality, outputStream);
521
+ data = outputStream.toByteArray();
522
+ }
523
+ }
524
+
525
+ if (!storeToFile) {
526
+ String encodedImage = Base64.encodeToString(data, Base64.NO_WRAP);
527
+
528
+ eventListener.onPictureTaken(encodedImage);
529
+ } else {
530
+ String path = getTempFilePath();
531
+ FileOutputStream out = new FileOutputStream(path);
532
+ out.write(data);
533
+ out.close();
534
+ eventListener.onPictureTaken(path);
535
+ }
536
+ Log.d(TAG, "CameraPreview pictureTakenHandler called back");
537
+ } catch (OutOfMemoryError e) {
538
+ // most likely failed to allocate memory for rotateBitmap
539
+ Log.d(TAG, "CameraPreview OutOfMemoryError");
540
+ // failed to allocate memory
541
+ eventListener.onPictureTakenError("Picture too large (memory)");
542
+ } catch (IOException e) {
543
+ Log.d(TAG, "CameraPreview IOException");
544
+ eventListener.onPictureTakenError("IO Error when extracting exif");
545
+ } catch (Exception e) {
546
+ Log.d(TAG, "CameraPreview onPictureTaken general exception");
547
+ } finally {
548
+ canTakePicture = true;
549
+ mCamera.startPreview();
550
+ }
551
+ }
552
+ };
553
+
554
+ private Camera.Size getOptimalPictureSize(
555
+ final int width,
556
+ final int height,
557
+ final Camera.Size previewSize,
558
+ final List<Camera.Size> supportedSizes
559
+ ) {
560
+ /*
561
+ get the supportedPictureSize that:
562
+ - matches exactly width and height
563
+ - has the closest aspect ratio to the preview aspect ratio
564
+ - has picture.width and picture.height closest to width and height
565
+ - has the highest supported picture width and height up to 2 Megapixel if width == 0 || height == 0
566
+ */
567
+ Camera.Size size = mCamera.new Size(width, height);
568
+
569
+ // convert to landscape if necessary
570
+ if (size.width < size.height) {
571
+ int temp = size.width;
572
+ size.width = size.height;
573
+ size.height = temp;
574
+ }
575
+
576
+ Camera.Size requestedSize = mCamera.new Size(size.width, size.height);
577
+
578
+ double previewAspectRatio = (double) previewSize.width / (double) previewSize.height;
579
+
580
+ if (previewAspectRatio < 1.0) {
581
+ // reset ratio to landscape
582
+ previewAspectRatio = 1.0 / previewAspectRatio;
583
+ }
584
+
585
+ Log.d(TAG, "CameraPreview previewAspectRatio " + previewAspectRatio);
586
+
587
+ double aspectTolerance = 0.1;
588
+ double bestDifference = Double.MAX_VALUE;
589
+
590
+ for (int i = 0; i < supportedSizes.size(); i++) {
591
+ Camera.Size supportedSize = supportedSizes.get(i);
592
+
593
+ // Perfect match
594
+ if (supportedSize.equals(requestedSize)) {
595
+ Log.d(TAG, "CameraPreview optimalPictureSize " + supportedSize.width + 'x' + supportedSize.height);
596
+ return supportedSize;
597
+ }
598
+
599
+ double difference = Math.abs(previewAspectRatio - ((double) supportedSize.width / (double) supportedSize.height));
600
+
601
+ if (difference < bestDifference - aspectTolerance) {
602
+ // better aspectRatio found
603
+ if ((width != 0 && height != 0) || (supportedSize.width * supportedSize.height < 2048 * 1024)) {
604
+ size.width = supportedSize.width;
605
+ size.height = supportedSize.height;
606
+ bestDifference = difference;
607
+ }
608
+ } else if (difference < bestDifference + aspectTolerance) {
609
+ // same aspectRatio found (within tolerance)
610
+ if (width == 0 || height == 0) {
611
+ // set highest supported resolution below 2 Megapixel
612
+ if ((size.width < supportedSize.width) && (supportedSize.width * supportedSize.height < 2048 * 1024)) {
613
+ size.width = supportedSize.width;
614
+ size.height = supportedSize.height;
615
+ }
616
+ } else {
617
+ // check if this pictureSize closer to requested width and height
618
+ if (
619
+ Math.abs(width * height - supportedSize.width * supportedSize.height) <
620
+ Math.abs(width * height - size.width * size.height)
621
+ ) {
622
+ size.width = supportedSize.width;
623
+ size.height = supportedSize.height;
624
+ }
625
+ }
626
+ }
627
+ }
628
+ Log.d(TAG, "CameraPreview optimalPictureSize " + size.width + 'x' + size.height);
629
+ return size;
630
+ }
631
+
632
+ static byte[] rotateNV21(final byte[] yuv, final int width, final int height, final int rotation) {
633
+ if (rotation == 0) return yuv;
634
+ if (rotation % 90 != 0 || rotation < 0 || rotation > 270) {
635
+ throw new IllegalArgumentException("0 <= rotation < 360, rotation % 90 == 0");
636
+ }
637
+
638
+ final byte[] output = new byte[yuv.length];
639
+ final int frameSize = width * height;
640
+ final boolean swap = rotation % 180 != 0;
641
+ final boolean xflip = rotation % 270 != 0;
642
+ final boolean yflip = rotation >= 180;
643
+
644
+ for (int j = 0; j < height; j++) {
645
+ for (int i = 0; i < width; i++) {
646
+ final int yIn = j * width + i;
647
+ final int uIn = frameSize + (j >> 1) * width + (i & ~1);
648
+ final int vIn = uIn + 1;
649
+
650
+ final int wOut = swap ? height : width;
651
+ final int hOut = swap ? width : height;
652
+ final int iSwapped = swap ? j : i;
653
+ final int jSwapped = swap ? i : j;
654
+ final int iOut = xflip ? wOut - iSwapped - 1 : iSwapped;
655
+ final int jOut = yflip ? hOut - jSwapped - 1 : jSwapped;
656
+
657
+ final int yOut = jOut * wOut + iOut;
658
+ final int uOut = frameSize + (jOut >> 1) * wOut + (iOut & ~1);
659
+ final int vOut = uOut + 1;
660
+
661
+ output[yOut] = (byte) (0xff & yuv[yIn]);
662
+ output[uOut] = (byte) (0xff & yuv[uIn]);
663
+ output[vOut] = (byte) (0xff & yuv[vIn]);
664
+ }
665
+ }
666
+ return output;
667
+ }
668
+
669
+ public void setOpacity(final float opacity) {
670
+ Log.d(TAG, "set opacity:" + opacity);
671
+ this.opacity = opacity;
672
+ mPreview.setOpacity(opacity);
673
+ }
674
+
675
+ public void takeSnapshot(final int quality) {
676
+ mCamera.setPreviewCallback(
677
+ new Camera.PreviewCallback() {
678
+ @Override
679
+ public void onPreviewFrame(byte[] bytes, Camera camera) {
680
+ try {
681
+ Camera.Parameters parameters = camera.getParameters();
682
+ Camera.Size size = parameters.getPreviewSize();
683
+ int orientation = mPreview.getDisplayOrientation();
684
+ if (mPreview.getCameraFacing() == Camera.CameraInfo.CAMERA_FACING_FRONT) {
685
+ bytes = rotateNV21(bytes, size.width, size.height, (360 - orientation) % 360);
686
+ } else {
687
+ bytes = rotateNV21(bytes, size.width, size.height, orientation);
688
+ }
689
+ // switch width/height when rotating 90/270 deg
690
+ Rect rect = orientation == 90 || orientation == 270
691
+ ? new Rect(0, 0, size.height, size.width)
692
+ : new Rect(0, 0, size.width, size.height);
693
+ YuvImage yuvImage = new YuvImage(bytes, parameters.getPreviewFormat(), rect.width(), rect.height(), null);
694
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
695
+ yuvImage.compressToJpeg(rect, quality, byteArrayOutputStream);
696
+ byte[] data = byteArrayOutputStream.toByteArray();
697
+ byteArrayOutputStream.close();
698
+ eventListener.onSnapshotTaken(Base64.encodeToString(data, Base64.NO_WRAP));
699
+ } catch (IOException e) {
700
+ Log.d(TAG, "CameraPreview IOException");
701
+ eventListener.onSnapshotTakenError("IO Error");
702
+ } finally {
703
+ mCamera.setPreviewCallback(null);
704
+ }
705
+ }
706
+ }
707
+ );
708
+ }
709
+
710
+ public void takePicture(final int width, final int height, final int quality) {
711
+ Log.d(TAG, "CameraPreview takePicture width: " + width + ", height: " + height + ", quality: " + quality);
712
+
713
+ if (mPreview != null) {
714
+ if (!canTakePicture) {
715
+ return;
716
+ }
717
+
718
+ canTakePicture = false;
719
+
720
+ new Thread() {
721
+ public void run() {
722
+ Camera.Parameters params = mCamera.getParameters();
723
+
724
+ Camera.Size size = getOptimalPictureSize(width, height, params.getPreviewSize(), params.getSupportedPictureSizes());
725
+ params.setPictureSize(size.width, size.height);
726
+ currentQuality = quality;
727
+
728
+ if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT && !storeToFile) {
729
+ // The image will be recompressed in the callback
730
+ params.setJpegQuality(99);
731
+ } else {
732
+ params.setJpegQuality(quality);
733
+ }
734
+
735
+ if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT && disableExifHeaderStripping) {
736
+ Activity activity = getActivity();
737
+ int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
738
+ int degrees = 0;
739
+ switch (rotation) {
740
+ case Surface.ROTATION_0:
741
+ degrees = 0;
742
+ break;
743
+ case Surface.ROTATION_90:
744
+ degrees = 180;
745
+ break;
746
+ case Surface.ROTATION_180:
747
+ degrees = 270;
748
+ break;
749
+ case Surface.ROTATION_270:
750
+ degrees = 0;
751
+ break;
752
+ }
753
+ int orientation;
754
+ Camera.CameraInfo info = new Camera.CameraInfo();
755
+ if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
756
+ orientation = (info.orientation + degrees) % 360;
757
+ if (degrees != 0) {
758
+ orientation = (360 - orientation) % 360;
759
+ }
760
+ } else {
761
+ orientation = (info.orientation - degrees + 360) % 360;
762
+ }
763
+ params.setRotation(orientation);
764
+ } else {
765
+ params.setRotation(mPreview.getDisplayOrientation());
766
+ }
767
+
768
+ mCamera.setParameters(params);
769
+ mCamera.takePicture(shutterCallback, null, jpegPictureCallback);
770
+ }
771
+ }
772
+ .start();
773
+ } else {
774
+ canTakePicture = true;
775
+ }
776
+ }
777
+
778
+ public void startRecord(
779
+ final String filePath,
780
+ final String camera,
781
+ final int width,
782
+ final int height,
783
+ final int quality,
784
+ final boolean withFlash,
785
+ final int maxDuration
786
+ ) {
787
+ Log.d(TAG, "CameraPreview startRecord camera: " + camera + " width: " + width + ", height: " + height + ", quality: " + quality);
788
+ Activity activity = getActivity();
789
+ muteStream(true, activity);
790
+ if (this.mRecordingState == RecordingState.STARTED) {
791
+ Log.d(TAG, "Already Recording");
792
+ return;
793
+ }
794
+
795
+ this.recordFilePath = filePath;
796
+ int mOrientationHint = calculateOrientationHint();
797
+ int videoWidth = 0; //set whatever
798
+ int videoHeight = 0; //set whatever
799
+
800
+ Camera.Parameters cameraParams = mCamera.getParameters();
801
+ if (withFlash) {
802
+ cameraParams.setFlashMode(withFlash ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
803
+ mCamera.setParameters(cameraParams);
804
+ mCamera.startPreview();
805
+ }
806
+
807
+ mCamera.unlock();
808
+ mRecorder = new MediaRecorder();
809
+
810
+ try {
811
+ mRecorder.setCamera(mCamera);
812
+
813
+ CamcorderProfile profile;
814
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_HIGH)) {
815
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_HIGH);
816
+ } else {
817
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_480P)) {
818
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_480P);
819
+ } else {
820
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_720P)) {
821
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_720P);
822
+ } else {
823
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_1080P)) {
824
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_1080P);
825
+ } else {
826
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_LOW);
827
+ }
828
+ }
829
+ }
830
+ }
831
+
832
+ mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
833
+ mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
834
+ mRecorder.setProfile(profile);
835
+ mRecorder.setOutputFile(filePath);
836
+ mRecorder.setOrientationHint(mOrientationHint);
837
+ mRecorder.setMaxDuration(maxDuration);
838
+
839
+ mRecorder.prepare();
840
+ Log.d(TAG, "Starting recording");
841
+ mRecorder.start();
842
+ eventListener.onStartRecordVideo();
843
+ } catch (IOException e) {
844
+ eventListener.onStartRecordVideoError(e.getMessage());
845
+ }
846
+ }
847
+
848
+ public int calculateOrientationHint() {
849
+ DisplayMetrics dm = new DisplayMetrics();
850
+ Camera.CameraInfo info = new Camera.CameraInfo();
851
+ Camera.getCameraInfo(defaultCameraId, info);
852
+ int cameraRotationOffset = info.orientation;
853
+ Activity activity = getActivity();
854
+
855
+ activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
856
+ int currentScreenRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
857
+
858
+ int degrees = 0;
859
+ switch (currentScreenRotation) {
860
+ case Surface.ROTATION_0:
861
+ degrees = 0;
862
+ break;
863
+ case Surface.ROTATION_90:
864
+ degrees = 90;
865
+ break;
866
+ case Surface.ROTATION_180:
867
+ degrees = 180;
868
+ break;
869
+ case Surface.ROTATION_270:
870
+ degrees = 270;
871
+ break;
872
+ }
873
+
874
+ int orientation;
875
+ if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
876
+ orientation = (cameraRotationOffset + degrees) % 360;
877
+ if (degrees != 0) {
878
+ orientation = (360 - orientation) % 360;
879
+ }
880
+ } else {
881
+ orientation = (cameraRotationOffset - degrees + 360) % 360;
882
+ }
883
+ Log.w(TAG, "************orientationHint ***********= " + orientation);
884
+
885
+ return orientation;
886
+ }
887
+
888
+ public void stopRecord() {
889
+ Log.d(TAG, "stopRecord");
890
+
891
+ try {
892
+ mRecorder.stop();
893
+ mRecorder.reset(); // clear recorder configuration
894
+ mRecorder.release(); // release the recorder object
895
+ mRecorder = null;
896
+ mCamera.lock();
897
+ Camera.Parameters cameraParams = mCamera.getParameters();
898
+ cameraParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
899
+ mCamera.setParameters(cameraParams);
900
+ mCamera.startPreview();
901
+ eventListener.onStopRecordVideo(this.recordFilePath);
902
+ } catch (Exception e) {
903
+ eventListener.onStopRecordVideoError(e.getMessage());
904
+ }
905
+ }
906
+
907
+ public void muteStream(boolean mute, Activity activity) {
908
+ AudioManager audioManager = ((AudioManager) activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE));
909
+ int direction = mute ? audioManager.ADJUST_MUTE : audioManager.ADJUST_UNMUTE;
910
+ }
911
+
912
+ public void setFocusArea(final int pointX, final int pointY, final Camera.AutoFocusCallback callback) {
913
+ if (mCamera != null) {
914
+ mCamera.cancelAutoFocus();
915
+
916
+ Camera.Parameters parameters = mCamera.getParameters();
917
+
918
+ Rect focusRect = calculateTapArea(pointX, pointY, 1f);
919
+ parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
920
+ parameters.setFocusAreas(Arrays.asList(new Camera.Area(focusRect, 1000)));
921
+
922
+ if (parameters.getMaxNumMeteringAreas() > 0) {
923
+ Rect meteringRect = calculateTapArea(pointX, pointY, 1.5f);
924
+ parameters.setMeteringAreas(Arrays.asList(new Camera.Area(meteringRect, 1000)));
925
+ }
926
+
927
+ try {
928
+ setCameraParameters(parameters);
929
+ mCamera.autoFocus(callback);
930
+ } catch (Exception e) {
931
+ Log.d(TAG, e.getMessage());
932
+ callback.onAutoFocus(false, this.mCamera);
933
+ }
934
+ }
935
+ }
936
+
937
+ private Rect calculateTapArea(float x, float y, float coefficient) {
938
+ if (x < 100) {
939
+ x = 100;
940
+ }
941
+ if (x > width - 100) {
942
+ x = width - 100;
943
+ }
944
+ if (y < 100) {
945
+ y = 100;
946
+ }
947
+ if (y > height - 100) {
948
+ y = height - 100;
949
+ }
950
+ return new Rect(
951
+ Math.round((x - 100) * 2000 / width - 1000),
952
+ Math.round((y - 100) * 2000 / height - 1000),
953
+ Math.round((x + 100) * 2000 / width - 1000),
954
+ Math.round((y + 100) * 2000 / height - 1000)
955
+ );
956
+ }
957
+
958
+ /**
959
+ * Determine the space between the first two fingers
960
+ */
961
+ private static float getFingerSpacing(MotionEvent event) {
962
+ // ...
963
+ float x = event.getX(0) - event.getX(1);
964
+ float y = event.getY(0) - event.getY(1);
965
+ return (float) Math.sqrt(x * x + y * y);
966
+ }
967
+ }