This repository has been archived by the owner on Jan 14, 2024. It is now read-only.
/
MainActivity.java
457 lines (412 loc) · 18.2 KB
/
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package com.example.ezequiel.camera2;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ezequiel.camera2.others.Camera2Source;
import com.example.ezequiel.camera2.others.FaceGraphic;
import com.example.ezequiel.camera2.utils.Utils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.example.ezequiel.camera2.others.CameraSource;
import com.example.ezequiel.camera2.others.CameraSourcePreview;
import com.example.ezequiel.camera2.others.GraphicOverlay;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Ezequiel Adrian Camera";
private Context context;
private static final int REQUEST_CAMERA_PERMISSION = 200;
private static final int REQUEST_STORAGE_PERMISSION = 201;
private TextView cameraVersion;
private ImageView ivAutoFocus;
// CAMERA VERSION ONE DECLARATIONS
private CameraSource mCameraSource = null;
// CAMERA VERSION TWO DECLARATIONS
private Camera2Source mCamera2Source = null;
// COMMON TO BOTH CAMERAS
private CameraSourcePreview mPreview;
private FaceDetector previewFaceDetector = null;
private GraphicOverlay mGraphicOverlay;
private FaceGraphic mFaceGraphic;
private boolean wasActivityResumed = false;
// DEFAULT CAMERA BEING OPENED
private boolean usingFrontCamera = true;
// MUST BE CAREFUL USING THIS VARIABLE.
// ANY ATTEMPT TO START CAMERA2 ON API < 21 WILL CRASH.
private boolean useCamera2 = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
context = getApplicationContext();
Button takePictureButton = (Button) findViewById(R.id.btn_takepicture);
Button switchButton = (Button) findViewById(R.id.btn_switch);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
cameraVersion = (TextView) findViewById(R.id.cameraVersion);
ivAutoFocus = (ImageView) findViewById(R.id.ivAutoFocus);
if(checkGooglePlayAvailability()) {
requestPermissionThenOpenCamera();
switchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(usingFrontCamera) {
stopCameraSource();
createCameraSourceBack();
usingFrontCamera = false;
} else {
stopCameraSource();
createCameraSourceFront();
usingFrontCamera = true;
}
}
});
takePictureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(useCamera2) {
if(mCamera2Source != null)mCamera2Source.takePicture(camera2SourceShutterCallback, camera2SourcePictureCallback);
} else {
if(mCameraSource != null)mCameraSource.takePicture(cameraSourceShutterCallback, cameraSourcePictureCallback);
}
}
});
mPreview.setOnTouchListener(CameraPreviewTouchListener);
}
}
final CameraSource.ShutterCallback cameraSourceShutterCallback = new CameraSource.ShutterCallback() {@Override public void onShutter() {Log.d(TAG, "Shutter Callback!");}};
final CameraSource.PictureCallback cameraSourcePictureCallback = new CameraSource.PictureCallback() {
@Override
public void onPictureTaken(Bitmap picture) {
Log.d(TAG, "Taken picture is here!");
FileOutputStream out = null;
try {
out = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "/camera_picture.png"));
picture.compress(Bitmap.CompressFormat.JPEG, 95, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
final Camera2Source.ShutterCallback camera2SourceShutterCallback = new Camera2Source.ShutterCallback() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onShutter() {Log.d(TAG, "Shutter Callback for CAMERA2");}
};
final Camera2Source.PictureCallback camera2SourcePictureCallback = new Camera2Source.PictureCallback() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onPictureTaken(Image image) {
Log.d(TAG, "Taken picture is here!");
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
Bitmap picture = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);
FileOutputStream out = null;
try {
out = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "/camera2_picture.png"));
picture.compress(Bitmap.CompressFormat.JPEG, 95, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
private boolean checkGooglePlayAvailability() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context);
if(resultCode == ConnectionResult.SUCCESS) {
return true;
} else {
if(googleApiAvailability.isUserResolvableError(resultCode)) {
googleApiAvailability.getErrorDialog(MainActivity.this, resultCode, 2404).show();
}
}
return false;
}
private void requestPermissionThenOpenCamera() {
if(ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
useCamera2 = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
createCameraSourceFront();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
}
private void createCameraSourceFront() {
previewFaceDetector = new FaceDetector.Builder(context)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.FAST_MODE)
.setProminentFaceOnly(true)
.setTrackingEnabled(true)
.build();
if(previewFaceDetector.isOperational()) {
previewFaceDetector.setProcessor(new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory()).build());
} else {
Toast.makeText(context, "FACE DETECTION NOT AVAILABLE", Toast.LENGTH_SHORT).show();
}
if(useCamera2) {
mCamera2Source = new Camera2Source.Builder(context, previewFaceDetector)
.setFocusMode(Camera2Source.CAMERA_AF_AUTO)
.setFlashMode(Camera2Source.CAMERA_FLASH_AUTO)
.setFacing(Camera2Source.CAMERA_FACING_FRONT)
.build();
//IF CAMERA2 HARDWARE LEVEL IS LEGACY, CAMERA2 IS NOT NATIVE.
//WE WILL USE CAMERA1.
if(mCamera2Source.isCamera2Native()) {
startCameraSource();
} else {
useCamera2 = false;
if(usingFrontCamera) createCameraSourceFront(); else createCameraSourceBack();
}
} else {
mCameraSource = new CameraSource.Builder(context, previewFaceDetector)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
startCameraSource();
}
}
private void createCameraSourceBack() {
previewFaceDetector = new FaceDetector.Builder(context)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.FAST_MODE)
.setProminentFaceOnly(true)
.setTrackingEnabled(true)
.build();
if(previewFaceDetector.isOperational()) {
previewFaceDetector.setProcessor(new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory()).build());
} else {
Toast.makeText(context, "FACE DETECTION NOT AVAILABLE", Toast.LENGTH_SHORT).show();
}
if(useCamera2) {
mCamera2Source = new Camera2Source.Builder(context, previewFaceDetector)
.setFocusMode(Camera2Source.CAMERA_AF_AUTO)
.setFlashMode(Camera2Source.CAMERA_FLASH_AUTO)
.setFacing(Camera2Source.CAMERA_FACING_BACK)
.build();
//IF CAMERA2 HARDWARE LEVEL IS LEGACY, CAMERA2 IS NOT NATIVE.
//WE WILL USE CAMERA1.
if(mCamera2Source.isCamera2Native()) {
startCameraSource();
} else {
useCamera2 = false;
if(usingFrontCamera) createCameraSourceFront(); else createCameraSourceBack();
}
} else {
mCameraSource = new CameraSource.Builder(context, previewFaceDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(30.0f)
.build();
startCameraSource();
}
}
private void startCameraSource() {
if(useCamera2) {
if(mCamera2Source != null) {
cameraVersion.setText("Camera 2");
try {mPreview.start(mCamera2Source, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source 2.", e);
mCamera2Source.release();
mCamera2Source = null;
}
}
} else {
if (mCameraSource != null) {
cameraVersion.setText("Camera 1");
try {mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
}
private void stopCameraSource() {
mPreview.stop();
}
private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
@Override
public Tracker<Face> create(Face face) {
return new GraphicFaceTracker(mGraphicOverlay);
}
}
private class GraphicFaceTracker extends Tracker<Face> {
private GraphicOverlay mOverlay;
GraphicFaceTracker(GraphicOverlay overlay) {
mOverlay = overlay;
mFaceGraphic = new FaceGraphic(overlay, context);
}
/**
* Start tracking the detected face instance within the face overlay.
*/
@Override
public void onNewItem(int faceId, Face item) {
mFaceGraphic.setId(faceId);
}
/**
* Update the position/characteristics of the face within the overlay.
*/
@Override
public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
mOverlay.add(mFaceGraphic);
mFaceGraphic.updateFace(face);
}
/**
* Hide the graphic when the corresponding face was not detected. This can happen for
* intermediate frames temporarily (e.g., if the face was momentarily blocked from
* view).
*/
@Override
public void onMissing(FaceDetector.Detections<Face> detectionResults) {
mFaceGraphic.goneFace();
mOverlay.remove(mFaceGraphic);
}
/**
* Called when the face is assumed to be gone for good. Remove the graphic annotation from
* the overlay.
*/
@Override
public void onDone() {
mFaceGraphic.goneFace();
mOverlay.remove(mFaceGraphic);
}
}
private final CameraSourcePreview.OnTouchListener CameraPreviewTouchListener = new CameraSourcePreview.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent pEvent) {
v.onTouchEvent(pEvent);
if (pEvent.getAction() == MotionEvent.ACTION_DOWN) {
int autoFocusX = (int) (pEvent.getX() - Utils.dpToPx(60)/2);
int autoFocusY = (int) (pEvent.getY() - Utils.dpToPx(60)/2);
ivAutoFocus.setTranslationX(autoFocusX);
ivAutoFocus.setTranslationY(autoFocusY);
ivAutoFocus.setVisibility(View.VISIBLE);
ivAutoFocus.bringToFront();
if(useCamera2) {
if(mCamera2Source != null) {
mCamera2Source.autoFocus(new Camera2Source.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success) {
runOnUiThread(new Runnable() {
@Override public void run() {ivAutoFocus.setVisibility(View.GONE);}
});
}
}, pEvent, v.getWidth(), v.getHeight());
} else {
ivAutoFocus.setVisibility(View.GONE);
}
} else {
if(mCameraSource != null) {
mCameraSource.autoFocus(new CameraSource.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success) {
runOnUiThread(new Runnable() {
@Override public void run() {ivAutoFocus.setVisibility(View.GONE);}
});
}
});
} else {
ivAutoFocus.setVisibility(View.GONE);
}
}
}
return false;
}
};
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
requestPermissionThenOpenCamera();
} else {
Toast.makeText(MainActivity.this, "CAMERA PERMISSION REQUIRED", Toast.LENGTH_LONG).show();
finish();
}
}
if(requestCode == REQUEST_STORAGE_PERMISSION) {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
requestPermissionThenOpenCamera();
} else {
Toast.makeText(MainActivity.this, "STORAGE PERMISSION REQUIRED", Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void onResume() {
super.onResume();
if(wasActivityResumed)
//If the CAMERA2 is paused then resumed, it won't start again unless creating the whole camera again.
if(useCamera2) {
if(usingFrontCamera) {
createCameraSourceFront();
} else {
createCameraSourceBack();
}
} else {
startCameraSource();
}
}
@Override
protected void onPause() {
super.onPause();
wasActivityResumed = true;
stopCameraSource();
}
@Override
protected void onDestroy() {
super.onDestroy();
stopCameraSource();
if(previewFaceDetector != null) {
previewFaceDetector.release();
}
}
}