Cделать скрин камеры внутри приложения в android

Скажу коротко. У меня есть свое приложение на android, делаю его на Java. Я смогла сделать камеру в своем приложении, которая никак не связанна на устройстве. Проблема в том, что я хочу захватить изображение с камеры, и сохранить его в галерею. Делаю это через скрин, но кроме деталей вокруг ничего не получается( Камера сама - черный квадрат. Как мне сделать скрин этой камеры?!! Должно происходить это при нажатии кнопки Вот код: VideFace... .java

public class VideoFaceDetectionActivity extends AppCompatActivity {


    static final int REQUEST_IMAGE_CAPTURE = 1;

    ImageButton button;
    CameraPreview mPreview;
    GraphicOverlay mGraphicOverlay;
    CameraSource mCameraSource;

    private static final String TAG = "VideoFaceDetection";
    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private static final int RC_HANDLE_GMS = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_face_detection);


        button = findViewById(R.id.takepicture);
        mPreview = findViewById(R.id.preview);
        mGraphicOverlay = findViewById(R.id.faceOverlay);



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//            takeScreenShot();


            }


//            private void takeScreenshot() {
//                Date now = new Date();
//                android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
//
//
//                try {
//
//                    // image naming and path  to include sd card  appending name you choose for file
//                    String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
//
//                    // create bitmap screen capture
//            View view = getWindow().getDecorView().getRootView();
//                    view.setDrawingCacheEnabled(true);
//                    Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), view.getWidth() / 38, view.getHeight() / 7, view.getWidth() - 60, view.getHeight() - 560);
//                    view.setDrawingCacheEnabled(false);
//                    view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
//
//
//                    BitmapFactory.Options options = new BitmapFactory.Options();
//                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
//
//                    File imageFile = new File(mPath);
//
//                    FileOutputStream outputStream = new FileOutputStream(imageFile);
//                    int quality = 100;
//                    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
//                    outputStream.flush();
//                    outputStream.close();
//
//                    openScreenshot(imageFile);
//                } catch (Throwable e) {
//                    // Several error may come out with file handling or DOM
//                    e.printStackTrace();
//                }
//
//            }
//
//
//            private void openScreenshot(File imageFile) {
//                Intent intent = new Intent();
//                intent.setAction(Intent.ACTION_VIEW);
//                Uri uri = Uri.fromFile(imageFile);
//                intent.setDataAndType(uri, "image/*");
//                startActivity(intent);
//            }

        });





//        Запрос на разрешения запуска камеры
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // permission not granted, initiate request
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }
        createCameraSource ();
    }



    private void createCameraSource () {
            Context context = getApplicationContext();
            FaceDetector detector = new FaceDetector.Builder(context)
                    .setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
                    .build();

            detector.setProcessor(
                    new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory())
                            .build());

            mCameraSource = new CameraSource.Builder(context, detector)
                    .setRequestedPreviewSize(640, 480)
                    .setFacing(CameraSource.CAMERA_FACING_FRONT)
                    .setRequestedFps(100.0f)
                    .build();
        }

        /**
         * Restarts the camera.
         */
        @Override
        protected void onResume () {
            super.onResume();

            startCameraSource();
        }
        /**
         * Stops the camera.
         */
        @Override
        protected void onPause () {
            if (mPreview != null) {
                mPreview.release();
                mPreview = null;
            }

            super.onPause();
        }
        /**
         * Releases the resources associated with the camera source, the associated detector, and the
         * rest of the processing pipeline.
         */
        @Override
        protected void onDestroy () {
            super.onDestroy();
            if (mCameraSource != null) {
                mCameraSource.release();
            }
        }
        private void startCameraSource () {
            // check that the device has play services available.
            int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext());
            if (code != ConnectionResult.SUCCESS) {
                Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
                dlg.show();
            }
            if (mCameraSource != null) {
                try {
                    mPreview.start(mCameraSource, mGraphicOverlay);
                } catch (IOException e) {
                    Log.e(TAG, "Unable to start camera source.", e);
                    mCameraSource.release();
                    mCameraSource = null;
                }
            }
        }
        /**
         * Factory for creating a face tracker to be associated with a new face.  The multiprocessor
         * uses this factory to create face trackers as needed -- one for each individual.
         */
        private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
            @Override
            public Tracker<Face> create(Face face) {
                return new GraphicFaceTracker(mGraphicOverlay);
            }
        }


    }

VideoFace... .xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@null"
    tools:context=".VideoFaceDetectionActivity">


    <com.maskbom.cam.CameraPreview
        android:id="@+id/preview"
        android:layout_width="1355px"
        android:layout_height="1355px"
        android:layout_marginLeft="30px"
        android:layout_marginTop="276px"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.maskbom.cam.GraphicOverlay
        android:id="@+id/faceOverlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <ImageButton
        android:layout_width="128px"
        android:layout_height="85px"
        android:layout_marginLeft="118px"
        android:layout_marginTop="84px"
        android:background="@null"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/gallery_button" />

    <ImageView
        android:layout_width="192px"
        android:layout_height="185px"
        app:srcCompat="@drawable/logo_camera"
        android:layout_marginLeft="446px"
        android:layout_marginTop="49px"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageButton
        android:layout_width="132px"
        android:layout_height="85px"
        android:layout_marginLeft="830px"
        android:layout_marginTop="84px"
        android:background="@null"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/turn" />

    <ImageButton
        android:id="@+id/takepicture"
        android:layout_width="222px"
        android:layout_height="205px"
        android:layout_marginLeft="429px"
        android:layout_marginTop="1670px"
        android:background="@null"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/startcamera_button" />


</RelativeLayout >

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.maskbom.cam">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar"
        >
        <activity android:name=".EntranceActivity"></activity>
        <activity android:name=".SignupActivity" />
        <activity android:name=".FaceDetectionActivity" />
        <activity android:name=".VideoFaceDetectionActivity" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

CameraPreview.java

public class CameraPreview extends ViewGroup {
    private static final String TAG = "CameraPreview";

    private Context mContext;
    private SurfaceView mSurfaceView;
    private boolean mStartRequested;
    private boolean mSurfaceAvailable;
    private CameraSource mCameraSource;

    private GraphicOverlay mOverlay;

    public CameraPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mStartRequested = false;
        mSurfaceAvailable = false;

        mSurfaceView = new SurfaceView(context);
        mSurfaceView.getHolder().addCallback(new SurfaceCallback());
        addView(mSurfaceView);
    }

    public void start(CameraSource cameraSource) throws IOException {
        if (cameraSource == null) {
            stop();
        }

        mCameraSource = cameraSource;

        if (mCameraSource != null) {
            mStartRequested = true;
            startIfReady();
        }
    }

    public void start(CameraSource cameraSource, GraphicOverlay overlay) throws IOException {
        mOverlay = overlay;
        start(cameraSource);
    }

    public void stop() {
        if (mCameraSource != null) {
            mCameraSource.stop();
        }
    }

    public void release() {
        if (mCameraSource != null) {
            mCameraSource.release();
            mCameraSource = null;
        }
    }

    @SuppressLint("MissingPermission")
    private void startIfReady() throws IOException {
        if (mStartRequested && mSurfaceAvailable) {
            mCameraSource.start(mSurfaceView.getHolder());
            if (mOverlay != null) {
                Size size = mCameraSource.getPreviewSize();
                int min = Math.min(size.getWidth(), size.getHeight());
                int max = Math.max(size.getWidth(), size.getHeight());
                if (isPortraitMode()) {
                    // Swap width and height sizes when in portrait, since it will be rotated by
                    // 90 degrees
                    mOverlay.setCameraInfo(min, max, mCameraSource.getCameraFacing());
                } else {
                    mOverlay.setCameraInfo(max, min, mCameraSource.getCameraFacing());
                }
                mOverlay.clear();
            }
            mStartRequested = false;
        }
    }



    private class SurfaceCallback implements SurfaceHolder.Callback {
        @Override
        public void surfaceCreated(SurfaceHolder surface) {
            mSurfaceAvailable = true;
            try {
                startIfReady();
            } catch (IOException e) {
                Log.e(TAG, "Could not start camera source.", e);
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surface) {
            mSurfaceAvailable = false;
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int width = 320;
        int height = 240;
        if (mCameraSource != null) {
            Size size = mCameraSource.getPreviewSize();
            if (size != null) {
                width = size.getWidth();
                height = size.getHeight();
            }
        }

        // Swap width and height sizes when in portrait, since it will be rotated 90 degrees
        if (isPortraitMode()) {
            int tmp = width;
            width = height;
            height = tmp;
        }

        final int layoutWidth = right - left;
        final int layoutHeight = bottom - top;

        // Computes height and width for potentially doing fit width.
        int childWidth = layoutWidth;
        int childHeight = (int)(((float) layoutWidth / (float) width) * height);

        // If height is too tall using fit width, does fit height instead.
        if (childHeight > layoutHeight) {
            childHeight = layoutHeight;
            childWidth = (int)(((float) layoutHeight / (float) height) * width);
        }

        for (int i = 0; i < getChildCount(); ++i) {
            getChildAt(i).layout(0, 0, childWidth, childHeight);
        }

        try {
            startIfReady();
        } catch (IOException e) {
            Log.e(TAG, "Could not start camera source.", e);
        }
    }

    private boolean isPortraitMode() {
        int orientation = mContext.getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            return false;
        }
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            return true;
        }

        Log.d(TAG, "isPortraitMode returning false by default");
        return false;
    }






}

Ответы (0 шт):