简体   繁体   English

如何在Android中使用相机捕获图像和视频?

[英]How to use camera in android to capture image and video?

How to use camera in android so that the user can toggle between the camera mode and recorder mode whilst in the same camera app, as you can see the small slide control in the center of the right side of the image below. 如何在Android中使用相机,以便用户可以在相同的相机应用程序中在相机模式和录像机模式之间切换,因为您可以在下方图像右侧中央看到小滑动控件。

滑动控件以红色圈出。

The stock camera app is open source. 相机应用程序是开源的。 Why not just take a look at how it is implemented? 为什么不看看它是如何实现的?

Use Tow Button One For Image and Other for Video in UI.... 使用拖动按钮一个用于图像和其他用于视频在UI ....

/****  Camera / Video Demo ****************/
public class CameraDemoActivity extends Activity {
    // Activity request codes
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    // directory name to store captured images and videos
    private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

    private Uri fileUri; // file url to store image/video

    private ImageView imgPreview;
    private VideoView videoPreview;
    private Button btnCapturePicture, btnRecordVideo;

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

        imgPreview = (ImageView) findViewById(R.id.imgPreview);
        videoPreview = (VideoView) findViewById(R.id.videoPreview);
        btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
        btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);

        /*
         * Capture image button click event
         */
        btnCapturePicture.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // capture picture
                captureImage();
            }
        });

        /*
         * Record video button click event
         */
        btnRecordVideo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // record video
                recordVideo();
            }
        });

        // Checking camera availability
        if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Your device doesn't support camera",
                    Toast.LENGTH_LONG).show();
            // will close the app if the device does't have camera
            finish();
        }
    }

    /**
     * Checking device has camera hardware or not
     * */
    private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /*
     * Capturing Camera Image will lauch camera app requrest image capture
     */
    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

    /*
     * Here we store the file url as it will be 
     * null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    /*
     * Recording video
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

        // set video quality
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the 
                                                           // image file
                                                           // name

        // start the video capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
    }

    /**
     * Receiving activity result method 
     * will be called after closing the camera
     * */
    @Override
    protected void onActivityResult(int requestCode, 
                                    int resultCode, Intent data) {

        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                // display it in image view
                previewCapturedImage();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // video successfully recorded
                // preview the recorded video
                previewVideo();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    /*
     * Display image from a path to ImageView
     */
    private void previewCapturedImage() {
        try {
            // hide video preview
            videoPreview.setVisibility(View.GONE);

            imgPreview.setVisibility(View.VISIBLE);

            // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();

            // downsizing image as it throws OutOfMemory Exception for larger
            // images
            options.inSampleSize = 8;

            final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                    options);

            imgPreview.setImageBitmap(bitmap);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /*
     * Previewing recorded video
     */
    private void previewVideo() {
        try {
            // hide image preview
            imgPreview.setVisibility(View.GONE);

            videoPreview.setVisibility(View.VISIBLE);
            videoPreview.setVideoPath(fileUri.getPath());
            // start playing
            videoPreview.pause();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ------------ Helper Methods ---------------------- 
     * */

    /*
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /*
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard
        // location.getExternalStoragePublicDirectory(
        // Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
        File mediaStorageDir = new File(
                Environment
                        .getExternalStorageDirectory(),
                IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
}

Add toggle button and set some value in it. 添加切换按钮并在其中设置一些值。 let say 0 or 1 and then capture image/record video button. 让我们说0或1,然后捕捉图像/录制视频按钮。 and when toggle value is 0 call camera method and when toggle value is 1 call video method. 当切换值为0时调用摄像机方法,当切换值为1时调用视频方法。

here is code for camera and video recording 这是相机和视频录制的代码

Capture image 捕获图像

Record Video 录视频

implement both classes methods in one class. 在一个类中实现两个类方法。 and then call onSnapClick for camera and startRecording() for video. 然后调用onSnapClick for camera和startRecording()获取视频。

Hope this will help. 希望这会有所帮助。

Try to use default functionality of camera and video like this- 尝试使用相机和视频的默认功能,如下所示 -

Intent intent1    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    String fileName = "KeyICamImage"+System.currentTimeMillis()+".JPG";
                    String mPathImage = Environment.getExternalStorageDirectory()+ "/" + fileName;
                    file = new File(mPathImage);
                    mImageCaptureUri= Uri.fromFile( file );

                    try 
                    {

                        intent1.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
                        startActivityForResult(intent1, PICK_FROM_CAMERA);
                    } 

                    catch (Exception e) 
                    {
                    e.printStackTrace();
                    }
                }
            });

I don't know is it works or not, but try this 我不知道它是否有效,但试试这个

You should have MediaRecorder recorder; Camera camera; 你应该有MediaRecorder recorder; Camera camera; MediaRecorder recorder; Camera camera;

Try to switching between video and photo by using camera.setPreviewDisplay(holder); 尝试使用camera.setPreviewDisplay(holder);在视频和照片之间切换camera.setPreviewDisplay(holder); or recorder.setPreviewDisplay(holder); 或者recorder.setPreviewDisplay(holder); in your surfaceCreated(SurfaceHolder holder) . 在你的surfaceCreated(SurfaceHolder holder) When you switching you should recreate surfaceView. 切换时应重新创建surfaceView。 Stock camera app recreates whole activity. 相机应用程序重新创建整个活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM