package com.;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.Face;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.iflytek.yl.R;
import com.iflytek.yl.common.base.BaseTitleActivity;
import com.iflytek.yl.common.util.YlLogger;
import com.iflytek.yl.common.volley.YLVolleyUtil;
import com.iflytek.yl.common.widget.BaseToast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.UUID;

public class DetectFaceActivity extends BaseTitleActivity implements View.OnClickListener {

    private CameraManager cManager;
    private static String TAG = "DetectFaceActivity"; Private static final SparseIntArray ORIENTATIONS = New SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } private TextureView cView; Private RelativeLayout Capture_crop_Layout; private RelativeLayout capture_crop_layout; private Surface previewSurface; Surface Private ImageReader cImageReader; private Surface captureSurface; // Take a picture of the Surface HandlerThread cHandlerThread; // Camera processing thread Handler cHandler; CameraDevice cDevice; CameraCaptureSession cSession; CameraDevice.StateCallback cDeviceOpenCallback = null; CaptureRequest.Builder previewRequestBuilder; // Build CaptureRequest previewRequest; / / preview request CameraCaptureSession CaptureCallback previewCallback; Capturerequest. Builder captureRequestBuilder; CaptureRequest captureRequest; CameraCaptureSession.CaptureCallback captureCallback; int[] faceDetectModes; // Rect rRect; // Camera image rectangle Size cPixelSize; // Camera imaging size int cOrientation; Size captureSize; boolean isFront; private ImageView scan; private YLVolleyUtil volleyUtil; private Handler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(R.layout.activity_faceverify); initVIew(); } /** * Initialize interface */ private voidinitVIew() {
        mHandler = new InnerHandler(this);
//        volleyUtil = new YLVolleyUtil(this, mHandler);

        cView = (TextureView) findViewById(R.id.sfv_preview);
        scan = (ImageView) findViewById(R.id.capture_scan_line);
        capture_crop_layout = (RelativeLayout) findViewById(R.id.capture_crop_layout);
        findViewById(R.id.face_photo).setOnClickListener(this);

        ViewGroup.LayoutParams params = capture_crop_layout.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels / 4 * 3;
        params.height = getResources().getDisplayMetrics().widthPixels / 4 * 3;
        capture_crop_layout.setLayoutParams(params);
    }

    private void startCamera() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                openCamera(true); }}, 100); } @SuppressLint("NewApi") private void openCamera(boolean isFront) { this.isFront = isFront; // Front camera String cId ="";
        if (isFront) {
            cId = CameraCharacteristics.LENS_FACING_BACK + "";
        } else {
            cId = CameraCharacteristics.LENS_FACING_FRONT + "";
        }
        cManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ! = PackageManager.PERMISSION_GRANTED) { Toast.makeText(this,"Please grant camera access.", Toast.LENGTH_LONG).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
        } else{/ / according to the camera ID, open webcam try {/ / access to open the related parameters of the camera CameraCharacteristics characteristics. = cManager getCameraCharacteristics (cId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); Size[] previewSizes = map.getOutputSizes(SurfaceTexture.class); [] captureSizes = map.getOutputSizes(imageFormat.jpeg); / / get photo size cOrientation = characteristics. The get (CameraCharacteristics. SENSOR_ORIENTATION); / / get the camera Angle the Rect cRect = characteristics. The get (CameraCharacteristics. SENSOR_INFO_ACTIVE_ARRAY_SIZE); / / get imaging area cPixelSize = characteristics. The get (CameraCharacteristics. SENSOR_INFO_PIXEL_ARRAY_SIZE); Yllogger. I (TAG,"Get camera Angle:"+ cOrientation); // Can be used to determine whether to support face detection, FaceDetectModes = Feature. get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES); / / support face detection model int maxFaceCount = characteristics. The get (CameraCharacteristics. STATISTICS_INFO_MAX_FACE_COUNT); // Maximum number of faces supported // This is 640*480, actually select previewSizes[2] from the preview size list; Size sSize = new Size(640, 480); Cview.getsurfacetexture ().setDefaultBufferSize(ssie.getwidth (), ssie.getheight ())); cManager.openCamera(cId, getCDeviceOpenCallback(), getCHandler()); TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0 , Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0); translateAnimation.setDuration(1300); translateAnimation.setRepeatCount(-1); translateAnimation.setRepeatMode(Animation.RESTART); scan.startAnimation(translateAnimation); } catch (CameraAccessException e) { YlLogger.i(TAG, Log.getStackTraceString(e)); }}} /** * Initializes and gets the camera open callback object. When ready, make a preview request */ @SuppressLint("NewApi")
    private CameraDevice.StateCallback getCDeviceOpenCallback() {
        if (cDeviceOpenCallback == null) {
            cDeviceOpenCallback = new CameraDevice.StateCallback() { @Override public void onOpened(@NonNull CameraDevice camera) { cDevice = camera; Try {// create Session, Need to finish the picture presents target (for preview and take pictures here Surface) initialization camera. CreateCaptureSession (arrays.aslist (getPreviewSurface (), getCaptureSurface ()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { cSession = session; Yllogger. I (TAG,"[Issue preview request]"); try { session.setRepeatingRequest(getPreviewRequest(), getPreviewCallback(), getCHandler()); } catch (CameraAccessException e) { YlLogger.i(TAG, Log.getStackTraceString(e)); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { session.close(); } }, getCHandler()); } catch (CameraAccessException e) { YlLogger.i(TAG, Log.getStackTraceString(e)); } } @Override public void onDisconnected(@NonNull CameraDevice camera) { camera.close(); } @Override public void onError(@NonNull CameraDevice camera, int error) { camera.close(); }}; }returncDeviceOpenCallback; } /** * initializes and gets the camera thread handling ** @return
     */
    private Handler getCHandler() {
        if(cHandler == null) {// Open a separate thread for the camera to use cHandlerThread = new HandlerThread("cHandlerThread");
            cHandlerThread.start();
            cHandler = new Handler(cHandlerThread.getLooper());
        }
        returncHandler; } /** * get the highest supported face detection level ** @return
     */
    private int getFaceDetectMode() {
        if (faceDetectModes == null) {
            return CaptureRequest.STATISTICS_FACE_DETECT_MODE_FULL;
        } else {
            returnfaceDetectModes[faceDetectModes.length - 1]; }} /** * Initializes and gets the preview callback object ** @return
     */
    @SuppressLint("NewApi")
    private CameraCaptureSession.CaptureCallback getPreviewCallback() {
        if (previewCallback == null) {
            previewCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { // onCameraImagePreviewed(result); }}; }returnpreviewCallback; } /** * generates and gets the preview request ** @return
     */
    @SuppressLint("NewApi")
    private CaptureRequest getPreviewRequest() {
        previewRequest = getPreviewRequestBuilder().build();
        returnpreviewRequest; } /** * initialize and get the preview request to build the object, for general configuration, and each time to get the face detection level configuration ** @return
     */
    @SuppressLint("NewApi")
    private CaptureRequest.Builder getPreviewRequestBuilder() {
        if(previewRequestBuilder == null) { try { previewRequestBuilder = cSession.getDevice().createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); previewRequestBuilder.addTarget(getPreviewSurface()); previewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); } catch (CameraAccessException e) {yllogger. I (TAG, log.getStackTraceString (e)); } } previewRequestBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, getFaceDetectMode()); / / set the level of face detection previewRequestBuilder. Set (CaptureRequest. JPEG_ORIENTATION, 0);returnpreviewRequestBuilder; } /** * get a preview of the Surface ** @return
     */
    private Surface getPreviewSurface() {
        if (previewSurface == null) {
            previewSurface = new Surface(cView.getSurfaceTexture());
        }
        returnpreviewSurface; } @param result */ @suppressLint ({}} @suppresslint ({}}"NewApi"."LocalSuppress"})
    private void onCameraImagePreviewed(CaptureResult result) {
        Face faces[] = result.get(CaptureResult.STATISTICS_FACES);
        YlLogger.i(TAG, "Face detected, take photo: faceLength=" + faces.length);
        if(faces.length > 0) {// A face is detected and the camera is executed executeCapture(); }} /** * Init photo related */ @suppresslint ("NewApi")
    private Surface getCaptureSurface() {
        if (cImageReader == null) {
            cImageReader = ImageReader.newInstance(getCaptureSize().getWidth(), getCaptureSize().getHeight(),
                    ImageFormat.JPEG, 2);
            cImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {@override public void onImageAvailable(ImageReader reader) {// Call onCaptureFinished(reader); } }, getCHandler()); captureSurface = cImageReader.getSurface(); }returncaptureSurface; } /** * get the photo size ** @return
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private Size getCaptureSize() {
        if(captureSize ! = null) {return captureSize;
        } else {
            returnnew Size(cView.getWidth(), cView.getHeight()); }} /** * Execute photo */ @suppresslint ("NewApi")
    private void executeCapture() {
        try {
            YlLogger.i(TAG, "Make a request");
            cSession.capture(getCaptureRequest(), getCaptureCallback(), getCHandler());
        } catch (CameraAccessException e) {
            YlLogger.i(TAG, Log.getStackTraceString(e));
        }
    }

    @SuppressLint("NewApi")
    private CaptureRequest getCaptureRequest() {
        captureRequest = getCaptureRequestBuilder().build();
        return captureRequest;
    }

    @SuppressLint("NewApi")
    private CaptureRequest.Builder getCaptureRequestBuilder() {
        if(captureRequestBuilder == null) { try { captureRequestBuilder = cSession.getDevice().createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); / / set the photo callback interface captureRequestBuilder. AddTarget (getCaptureSurface ()); //TODO 1 photo rotation int rotation = getWindowManager().getDefaultDisplay().getrotation (); int rotationTo = getOrientation(rotation); captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, rotationTo); } catch (CameraAccessException e) { YlLogger.i(TAG, Log.getStackTraceString(e)); }}return captureRequestBuilder;
    }

    @SuppressLint("NewApi")
    private CameraCaptureSession.CaptureCallback getCaptureCallback() {
        if (captureCallback == null) {
            captureCallback = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest
                        request, @NonNull TotalCaptureResult result) {
                }
            };
        }
        return captureCallback;
    }

    /**
     * Retrieves the JPEG orientation from the specified screen rotation.
     *
     * @param rotation The screen rotation.
     * @return The JPEG orientation (one of 0, 90, 270, and 360)
     */
    private int getOrientation(int rotation) {
        return(ORIENTATIONS.get(rotation) + cOrientation + 270) % 360; } @param reader */ @suppresslint ()"NewApi") private void onCaptureFinished(ImageReader reader) { Image image = reader.acquireLatestImage(); ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] data = new byte[buffer.remaining()]; buffer.get(data); image.close(); buffer.clear(); Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); showImage(bitmap); Runtime.getRuntime().gc(); } /** * @param image */ private void showImage(final Bitmap image) {mhandler.post (new)Runnable() {
            @Override
            public void run() { upload(image); }}); } private void upload(Bitmap face) {if (face == null) {
            BaseToast.showToast(getApplicationContext(), "Error taking photo, please try again!");
            return;
        }
        try {
            final File file = File.createTempFile(UUID.randomUUID().toString() + "".".jpg");
            int minWidth = Math.min(face.getWidth(), face.getHeight());
            int x = (face.getWidth() - minWidth) / 2;
            int y = (face.getHeight() - minWidth) / 2;
            Bitmap bitmap = Bitmap.createBitmap(face, x, y, minWidth, minWidth);
            resize(bitmap, file, 480, 480);

            Intent intent = new Intent();
            intent.putExtra("filePath", file.getAbsolutePath());
            setResult(RESULT_OK, intent);
            finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void deleteFace(File file) {
        if(file ! = null && file.exists()) { file.delete(); } } @SuppressLint("NewApi")
    private void closeCamera() {
        if(cSession ! = null) { try { cSession.stopRepeating(); } catch (CameraAccessException e) { e.printStackTrace(); } cSession.close(); cSession = null; }if(cDevice ! = null) { cDevice.close(); cDevice = null; }if(cImageReader ! = null) { cImageReader.close(); cImageReader = null; captureRequestBuilder = null; }if (cHandlerThread != null) {
            cHandlerThread.quitSafely();
            try {
                cHandlerThread.join();
                cHandlerThread = null;
                cHandler = null;
            } catch (InterruptedException e) {
                YlLogger.i(TAG, Log.getStackTraceString(e));
            }
        }

        if(captureRequestBuilder ! = null) { captureRequestBuilder.removeTarget(captureSurface); captureRequestBuilder = null; }if(captureSurface ! = null) { captureSurface.release(); captureSurface = null; }if(previewRequestBuilder ! = null) { previewRequestBuilder.removeTarget(previewSurface); previewRequestBuilder = null; }if(previewSurface ! = null) { previewSurface.release(); previewSurface = null; } } @Override protected voidonResume() {
        super.onResume();
        startCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeCamera();
    }

    private static class InnerHandler extends Handler {
        private WeakReference<DetectFaceActivity> mWeakReference;

        public InnerHandler(DetectFaceActivity activity) {
            super();
            this.mWeakReference = new WeakReference<DetectFaceActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mWeakReference == null || mWeakReference.get() == null) {
                return;
            }
            DetectFaceActivity activity = mWeakReference.get();
            if (activity == null) {
                return;
            }
            if (msg == null) {
                return;
            }
            switch (msg.what) {
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.face_photo:
                executeCapture();
                break;
            default:
                break; } } private void resize(Bitmap bitmap, File outputFile, int maxWidth, int maxHeight) { try { int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); // The image is larger than the maximum width and heightif (bitmapWidth > maxHeight || bitmapHeight > maxWidth) {
                floatWidthScale = maxWidth * 1.0f/bitmapWidth;floatHeightScale = maxHeight * 1.0f/bitmapHeight;float scale = Math.min(widthScale, heightScale);
                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false); } FileOutputStream out = new FileOutputStream(outputFile); try { bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (Exception e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); }}}Copy the code