Android -Camer使用!

Sstorge:是图像或视频应用程序生成目的只有可见的应用程序或共享,以便其他应用程序如画廊或其他媒体和社交应用程序可以使用它们吗?你想要的图片和视频是可用的,即使你的应用程序卸载吗?看看媒体文件保存部分如何实现这些选项。

The Basic:

Android框架支持通过摄像头API或捕捉图像和视频or camera Intent:

下面是相关的类:

1.     Camera这个类是主要的API控制设备摄像头。该类用于拍照和视频当你构建一个相机应用程序。

2.      SurfaceViewThis class is used to present a live camerapreview to the user.

3.      MediaRecorderThis class is used to record video from thecamera.

4.        Intent

An intentaction type of MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_VIDEO_CAPTURE can be used to capture images or videoswithout directly using the Camera object.

Manifest Declarations: 清单声明

开始前与摄像头API开发您的应用程序,你应该确保你的清单有适当的声明允许使用相机硬件和其他相关特性。

Camera Permission您的应用程序必须请求许可使用设备的相机。

<uses-permissionandroid:name="android.permission.CAMERA" />

Note:如果您使用的是相机通过一个Intent,您的应用程序不需要请求许可。

Camera Features :如果您使用的是相机通过一个意图,您的应用程序不需要请求许可。

<uses-featureandroid:name="android.hardware.camera" />

Storage Permission:如果您的应用程序保存图像或视频设备的外部存储器(SD卡),您还必须specify this in the manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

l  LocationPermission 如果您的应用程序标记图像与GPS定位信息,您必须请求许可位置:

<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" />

Using ExistingCamera Apps:一个快速的方法在应用程序中启用拍照或录像没有很多额外的代码是使用意图来调用现有的Android摄像头应用程序。相机意图发出请求来捕获一个图片或视频剪辑通过现有相机应用程序,然后将控制返回给应用程序。本节将向您展示如何捕获图像或视频使用这种技术。(Intent)

调用相机意图的过程遵循这些一般步骤:

1.     Composea Camera Intent: Createan Intent that requests an image or video,

MediaStore.ACTION_IMAGE_CAPTURE - Intent actiontype for requesting an image from an existing camera application.

MediaStore.ACTION_VIDEO_CAPTURE - Intent actiontype for requesting a video from an existing camera application.

 

2.         Startthe Camera Intent: use the startActivityForResult() 方法执行相机的意图。你开始的意图后,相机应用程序用户界面出现在设备屏幕上,用户可以拍照或录像。

3.         Receivethe Intent Result - Set up an onActivityResult()方法在应用程序中从摄像头接收回调函数和数据的意图。当用户完成拍一张照片或视频(或取消操作),系统调用这个方法。

Image capture intent

捕获图像使用相机的目的是快速的方法使应用程序能够以最少的编码拍照。图像捕捉意图可以包括以下额外的信息:

MediaStore.EXTRA_OUTPUT :这个设置需要一个Uri对象指定路径和文件名,您想保存图片。这个设置是可选的,但是强烈建议。如果不指定这个值,相机应用程序请求的图片保存在默认位置缺省名称,指定返回的意图的Intent.getData()。

 

下面的例子演示了如何构造一个图像捕获意图和执行它。getOutputMediaFileUri()方法在这个例子中是指储蓄媒体文件中所示的示例代码。

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // create Intent to take a picture and return control to the calling application
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

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

 

当startActivityForResult()方法执行,用户看到一个相机应用程序接口。在用户完成后拍照(或取消操作),用户界面返回到您的应用程序,你必须拦截onActivityResult()方法接收意图的结果和应用程序继续执行。如何接收完成的意图的信息,看到收到相机意图的结果。

 

Video capture intent

MediaStore.EXTRA_OUTPUT :

这个设置需要一个Uri对象指定路径和文件名,您想保存图片。这个设置是可选的,但是强烈建议。如果不指定这个值,相机应用程序请求的图片保存在默认位置缺省名称,指定返回的意图的Intent.getData()。

MediaStore.EXTRA_VIDEO_QUALITY :

这个值可以为最低质量和最小的文件大小是0或1的最高质量和更大的文件大小。MediaStore.EXTRA_DURATION_LIMIT 

将这个值设置为限制长度,以秒为单位,视频被抓获。

MediaStore.EXTRA_SIZE_LIMIT 

将这个值设置为限制文件大小,以字节为单位,被捕获的视频

例子:

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
private Uri fileUri;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //create new Intent
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);  // create a file to save the video
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name

    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high

    // start the Video Capture Intent
    startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}

Receiving camera intentresult

本节将向您展示如何从相机意图拦截回调应用程序可以做进一步处理捕获的图像或视频。

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Image captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Image saved to:\n" +
                     data.getData(), Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }
    }

    if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Video captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Video saved to:\n" +
                     data.getData(), Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the video capture
        } else {
            // Video capture failed, advise user
        }
    }
}

 

一旦你的活动获得成功的结果,捕获的图像或视频可以在指定的位置为您的应用程序访问。

 

Buildinga Camera App

 一些开发人员可能需要一个相机的用户界面定制他们的应用程序的外观或提供特殊功能。创建一个定制的相机活动需要更多的代码比使用一个意图,但它可以为您的用户提供一个更令人信服的体验。      的一般步骤为应用程序创建一个自定义相机界面如下:

The general steps for creating a custom camera interfacefor your application are as follows:

1.        创建代码来检查相机和请求访问的存在。

2.        创建一个相机预览SurfaceView进行了扩展,实现了SurfaceHolder接口的类。这个类预览现场相机的照片。

3.        一旦你有了摄像头预览类,创建一个视图布局包含预览和你想要的用户界面控件。

4.        SetupListeners for Capture Connect listeners for your interface controls to startimage or video capture in response to user actions, such as pressing a button.

5.        设置的代码捕获并保存照片或视频输出。

6.        使用相机后,应用程序必须正确地释放它,供其他应用程序使用。

相机硬件是一个共享资源,所以必须小心地管理您的应用程序不会撞上其他应用程序也可以使用它。以下部分将讨论如何检测摄像头硬件,如何请求访问一个相机,如何捕获图片或视频以及如何释放相机当您的应用程序使用它。

a)        检测我么的Manifest.xml的定义,你应该看看一个摄像头在运行时可用,执行检查 use the PackageManager.hasSystemFeature() method, 

我们这里有Camera?

/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

Android设备可以有多个摄像头,比如后面的相机摄影和视频通话的前置摄像头。Android 2.3(API级别9),后来允许您检查可用摄像机的数量在设备上使用Camera.getNumberOfCameras()方法。

Accessing cameras

 1.打开摄像头:如果您已经确定您的应用程序正在运行的设备有一个摄像头,你必须请求访问它通过相机的一个实例(除非你使用一个意图访问相机)访问主相机,使用Camera.open()方法并确保捕获任何异常,如以下代码所示:

/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}

设备上运行Android 2.3(API级别9)或更高版本,您可以使用Camera.open(int)。上面的示例代码将首先访问,后面的摄像头设备上与多个相机。

Checking camera features(摄像头的一些信息)

一旦你获得一个摄像头,你可以得到更多的信息关于它的功能使用Camera.getParameters()方法和检查返回的相机。参数对象支持功能。当使用API级别9或更高,使用Camera.getCameraInfo()来确定一个相机在前面或后面的设备,和图像的方向。

Creating a preview class

相机预览类是一个SurfaceView能够显示实时图像数据来自一个摄像头,这样用户就可以框架和捕捉照片或视频。

下面的示例代码演示了如何创建一个基本的相机预览类可以包含在一个视图布局。这个类实现了SurfaceHolder。回调是为了捕捉回调事件视图创建和销毁,这需要分配相机预览输入。

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
          // preview surface does not exist
          return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
          // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }
}

如果你想设置一个特定的大小为你的相机预览,设置在surfaceChanged()方法在评论中提到以上。当预览大小设置,您必须使用值getSupportedPreviewSizes()。不设置任意值setPreviewSize()方法。

 

Placing preview in alayout

相机预览类,如前一节所示的例子中,必须放置在一个活动的布局以及其他用户界面控件拍照或录像。本节将向您展示如何构建一个基本的布局和预览活动。

下面的布局代码提供了一个非常基本的视图,可以用来显示一个相机预览。在这个例子中,FrameLayout元素是相机预览类的容器。使用此布局类型,所以额外的图片信息或控件可以显示在相机预览图像。


   
   

   
   
  
    
    

  
    
    

   
   

 

在大多数设备,默认定位相机预览是风景。这个示例布局指定水平(景观)布局和下面的代码补丁应用于景观的方向。为简单起见在渲染相机预览,你应该改变你的应用程序的预览活动取向景观通过添加以下你的清单。


   
   
          
    
    

          
    
    
        
     
     
        
     
     
    
    
    

   
   

Note:一个相机预览没有横屏模式。从Android 2.2(API级别8),您可以使用setDisplayOrientation()方法设置预览图像的旋转。为了改变预览取向作为用户重新调整电话,在surfaceChanged预览类()方法,第一站的预览Camera.stopPreview()改变方向,然后再次启动预览Camera.startPreview()

 

在你的相机视图的活动中,添加您的预览类FrameLayout元素上面的例子所示。相机活动还必须确保它释放相机时暂停或关闭。下面的例子展示了如何修改相机活动连接中显示预览类创建一个预览类。

public class CameraActivity extends Activity {

    private Camera mCamera;
    private CameraPreview mPreview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Create an instance of Camera
        mCamera = getCameraInstance();

        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
        preview.addView(mPreview);
    }
}

 

Capturing picture

一旦你建立了一个预览类和视图布局来显示,您已经准备好开始捕获图像与您的应用程序。在您的应用程序代码中,必须设置监听器为你的用户界面控件响应用户动作通过一幅画

 

为了检索图像,使用Camera.takePicture()方法。这个方法取三个参数,接收数据从相机。为了以JPEG格式接收数据,您必须实现一个相机。 Camera.PictureCallback 接口接收图像数据并将它写入一个文件。下面的代码显示了相机的基本实现。PictureCallback接口收到相机保存图像

private PictureCallback mPicture = new PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (pictureFile == null){
            Log.d(TAG, "Error creating media file, check storage permissions: " +
                e.getMessage());
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }
};

 

通过调用Camera.takePicture触发器捕获图像()方法。下面的示例代码展示了如何从一个按钮View.OnClickListener调用这个方法。

// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
    new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // get an image from the camera
            mCamera.takePicture(null, null, mPicture);
        }
    }

记得释放相机对象通过调用Camera.release()当您的应用程序使用它!如何释放相机的更多信息,请参阅释放相机

 

Capturing videos

视频捕捉镜头使用Android框架需要仔细的管理对象,并配合MediaRecorder类。当与摄像头录制视频时,你必须管理Camera.lock()和Camera.unlock()调用允许MediaRecorder访问摄像头硬件,除了Camera.open()和Camera.release()调用。

与设备的相机拍照,捕捉视频需要非常特定的调用顺序。你必须按照特定的顺序执行成功的准备和捕获视频与您的应用程序,如下详细

1.   Open Camera - Use the Camera.open() to get aninstance of the camera object.

2.   Connect Preview - Prepare a live camera imagepreview by connecting a SurfaceView to thecamera usingCamera.setPreviewDisplay().

3.   Start Preview - Call Camera.startPreview() to begindisplaying the live camera images.

4.   Start Recording Video - The following steps must becompleted in order to successfully record video:

  1. setCamera() - Set the camera to be used for video capture, use your application's current instance ofCamera.
  2. setAudioSource() - Set the audio source, use MediaRecorder.AudioSource.CAMCORDER.
  3. setVideoSource() - Set the video source, use MediaRecorder.VideoSource.CAMERA.
  4. Set the video output format and encoding. For Android 2.2 (API Level 8) and higher, use theMediaRecorder.setProfile method, and get a profile instance using CamcorderProfile.get(). For versions of Android prior to 2.2, you must set the video output format and encoding parameters:
    1. setOutputFormat() - Set the output format, specify the default setting orMediaRecorder.OutputFormat.MPEG_4.
    2. setAudioEncoder() - Set the sound encoding type, specify the default setting orMediaRecorder.AudioEncoder.AMR_NB.
    3. setVideoEncoder() - Set the video encoding type, specify the default setting orMediaRecorder.VideoEncoder.MPEG_4_SP.
  5. setOutputFile() - Set the output file, use getOutputMediaFile(MEDIA_TYPE_VIDEO).toString() from the example method in the Saving Media Files section.

10.   setPreviewDisplay() -pecify SurfaceView预览布局元素为您的应用程序。使用相同的对象为连接指定预览。

  1. Prepare MediaRecorder - Prepare the MediaRecorder with provided configuration settings by callingMediaRecorder.prepare().
  2. Start MediaRecorder - Start recording video by calling MediaRecorder.start().
  3. Stop Recording Video - Call the following methods in order, to successfully complete a video recording:
    1. Stop MediaRecorder - Stop recording video by calling MediaRecorder.stop().
    2. Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by callingMediaRecorder.reset().
    3. Release MediaRecorder - Release the MediaRecorder by calling MediaRecorder.release().
    4. Lock the Camera - Lock the camera so that future MediaRecorder sessions can use it by callingCamera.lock(). Starting with Android 4.0 (API level 14), this call is not required unless theMediaRecorder.prepare() call fails.
  4. Stop the Preview - When your activity has finished using the camera, stop the preview usingCamera.stopPreview().
  5. Release Camera - Release the camera so that other applications can use it by calling Camera.release()
  6. Tip:如果您的应用程序通常用于录制视频,设置setRecordingHint(布尔)真正的开始之前你的预览。这个设置可以帮助减少所花费的时间开始记录。
Configuring MediaRecorde

使用MediaRecorder类当录制视频,你必须在一个特定的顺序执行的配置步骤,然后调用MediaRecorder.prepare()方法来检查和实施配置。下面的示例代码演示了如何正确配置和准备MediaRecorder类录像。

private boolean prepareVideoRecorder(){

    mCamera = getCameraInstance();
    mMediaRecorder = new MediaRecorder();

    // Step 1: Unlock and set camera to MediaRecorder
    mCamera.unlock();
    mMediaRecorder.setCamera(mCamera);

    // Step 2: Set sources
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    // Step 4: Set output file
    mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());

    // Step 5: Set the preview output
    mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

    // Step 6: Prepare configured MediaRecorder
    try {
        mMediaRecorder.prepare();
    } catch (IllegalStateException e) {
        Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
        releaseMediaRecorder();
        return false;
    } catch (IOException e) {
        Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
        releaseMediaRecorder();
        return false;
    }
    return true;
}

Android 2.2(API级别8)之前,您必须设置输出格式和编码格式参数直接使用CamcorderProfile代替。这种方法是通过以下代码:

<scriptsrc="https://code.csdn.net/snippets/1104698.js"></script>

MediaRecorder以下录像参数给出默认设置,然而,你可能想要调整这些设置为您的应用程序:

·        setVideoEncodingBitRate()

·        setVideoSize()

·        setVideoFrameRate()

·        setAudioEncodingBitRate()

·        setAudioChannels()

·        setAudioSamplingRate()

Starting and stopping MediaRecorder

当使用MediaRecorder类启动和停止录像,你必须遵循一个特定的顺序,如下所列。

1.   Unlock the camera with Camera.unlock()

2.   Configure MediaRecorder as shownin the code example above

3.   Start recording using MediaRecorder.start()

4.   Record the video

5.   Stop recording using MediaRecorder.stop()

6.   Release the media recorder with MediaRecorder.release()

7.   Lock the camera using Camera.lock()

Note:当完成一个录像,不释放相机,否则你的预览将会停止

 

private boolean isRecording = false;

// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
    new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isRecording) {
                // stop recording and release camera
                mMediaRecorder.stop();  // stop the recording
                releaseMediaRecorder(); // release the MediaRecorder object
                mCamera.lock();         // take camera access back from MediaRecorder

                // inform the user that recording has stopped
                setCaptureButtonText("Capture");
                isRecording = false;
            } else {
                // initialize video camera
                if (prepareVideoRecorder()) {
                    // Camera is available and unlocked, MediaRecorder is prepared,
                    // now you can start recording
                    mMediaRecorder.start();

                    // inform the user that recording has started
                    setCaptureButtonText("Stop");
                    isRecording = true;
                } else {
                    // prepare didn't work, release the camera
                    releaseMediaRecorder();
                    // inform user
                }
            }
        }
    }
);

在上面的例子中,prepareVideoRecorder()方法是指配置MediaRecorder中所示的示例代码。该方法负责锁定相机,配置和准备MediaRecorder实例

Releasing the camera

相机是一个资源共享的应用程序在设备上。您的应用程序可以利用相机相机的一个实例,你必须特别小心释放相机对象当应用程序停止使用它,一旦应用程序暂停(Activity.onPause())。如果您的应用程序不正确地释放相机,所有后续试图访问摄像机,包括那些通过自己的应用程序,将会失败,可能导致或其他应用程序关闭。      释放相机的一个实例对象,使用Camera.release()方法,如下所示的示例代码。

public class CameraActivity extends Activity {
    private Camera mCamera;
    private SurfaceView mPreview;
    private MediaRecorder mMediaRecorder;

    ...

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();   // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
}

SavingMedia Files

图片和视频等媒体文件创建的用户应该保存到外部存储设备的目录(SD卡)保护系统空间,并允许用户访问这些文件,没有他们的设备。有许多可能的目录位置保存在设备上媒体文件,但是只有两个标准位置应该考虑作为一个开发人员:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) -他的方法返回标准,共享和推荐位置保存图片和视频。这个目录是共享的(公共),所以其他应用程序可以很容易地发现,阅读、更改和删除文件保存在这个位置。如果您的应用程序用户卸载,媒体文件保存到这个位置不会被删除。为了避免干扰用户现有的图片和视频,你应该为应用程序创建子目录的媒体文件在这个目录,如下面的代码示例所示。这种方法可以在Android 2.2(API级别8),相当于调用API版本,早些时候看到储蓄共享文件

Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)

这个方法返回一个标准的位置保存图片和视频与您的应用程序。如果你的应用程序卸载,删除任何文件保存在这个位置。安全不执行文件在这个位置和其他应用程序可以读取、改变和删除它们。

 

下面的示例代码演示了如何创建一个文件或一个媒体文件,可以使用Uri位置当调用一个设备的相机与一个意图或作为构建的一部分相机应用。

public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
      return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_PICTURES), "MyCameraApp");
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").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;
}

 

CameraFeatures

Android支持广泛的相机功能你可以用你的相机控制应用程序,如图片格式,闪光模式,集中设置,和许多更多。本节列出了常见的相机功能,并简要讨论了如何使用它们。大多数相机功能可以访问和使用通过相机设置。参数对象。然而,有几个重要的功能,需要在Camera.Parameters超过简单的设置。这些功能都包含在以下部分:

计量和重点领域   人脸检测   时间流逝的视频

·        Metering andfocus areas

·        Face detection

·        Time lapse vide

Checking featureavailability

你可以检查相机的接收特性通过相机的参数对象的一个实例,并检查相关的方法。下面的代码示例显示了如何获得一个相机。参数对象和检查相机支持自动对焦功能:

/ get Camera parameters

Camera.Parameters params = mCamera.getParameters();

 

List<String> focusModes = params.getSupportedFocusModes();

if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {

  // Autofocus mode is supported

}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android相机开发是指在Android系统中使用相机功能进行应用开发的过程。Android系统提供了丰富的相机API,使开发者可以轻松地实现与相机相关的功能。 首先,要在Android应用中使用相机,需要先获取相机实例。可以通过Camera类来获取相机实例,其提供了与相机硬件进行交互的方法和属性。可以通过调用open()方法来打开相机,并通过设置参数来配置相机的各种属性,如照片分辨率、闪光灯模式等。 接下来,可以使用SurfaceView来预览相机所拍摄的画面。SurfaceView是Android中用于显示实时画面的控件,可以通过SurfaceHolder来获取并控制SurfaceView的显示。 在进行拍照操作时,可以通过设置Camera.PictureCallback接口的实现来获取相机所拍摄的照片数据,并将其保存到指定的文件中。可以通过调用takePicture()方法来触发拍照动作,并在PictureCallback的回调方法中处理照片数据。 除了拍照功能,Android相机开发还可以实现其他功能,如录制视频、切换摄像头等。可以通过设置MediaRecorder来实现视频录制功能,通过调用Camera类中的方法来切换前后摄像头。 Android相机开发需要注意相机资源的管理和释放。在使用相机之前,需要先获取相机的访问权限,并在不使用相机时及时释放相机资源,避免资源泄漏。 总之,Android相机开发提供了丰富的API和功能,使开发者可以灵活地利用相机进行应用开发,实现各种有趣的相机功能和交互体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值