Android 开发随手笔记之使用摄像头拍照

来源:互联网 发布:ubuntu 16.04卸载qq 编辑:程序博客网 时间:2024/04/30 11:01

在Android中,使用摄像头拍照一般有两种方法, 一种是调用系统自带的Camera,另一种是自己写一个摄像的界面。

      我们要添加如下权限:(在Androidmanifest.xml文件中添加权限)

?
1
2
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
    

1、调用系统Camera

      调用系统自带的Camera主要的步骤为:

(1)构造图片存储的路径名

(2)使用Intent启动Camera Activity

(3)将拍摄的图片写入到文件

(4)将图片显示在MainActivity中

      首先,构造图片名:

1
2
3
4
5
6
7
8
9
10
11
12
File filePath = newFile(Environment.getExternalStorageDirectory(), "myCamera");
if(!filePath.exists()){
 filePath.mkdirs();
}
fileName = newFile(filePath, System.currentTimeMillis() + ".jpg");
try{
 if(!fileName.exists()){
  fileName.createNewFile();
 }
}catch(Exception e){
 e.printStackTrace();
}

      然后,启动Camera Activity:

?
1
2
3
4
5
6
// intent用来启动系统自带的Camera
Intent intent = newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
// 将系统Camera的拍摄结果写入到文件
 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fileName));
// 启动intent对应的Activity,返回默认消息
 startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);

      最后,将图片显示在MainActivity内。这时,我们通过重载onActivityResult()方法来获取Camera返回的消息。

?
1
2
3
4
5
6
7
@Override
protectedvoid onActivityResult(intrequestCode, intresultCode, Intent data){
 if(requestCode == Activity.DEFAULT_KEYS_DIALER){
  // MainActivity接收Camera返回的消息,然后将已经写入的图片显示在ImageView内
  imageView.setImageURI(Uri.fromFile(fileName));
 }
}

完整代码为:

?
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
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.provider.MediaStore;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.ImageView;
importjava.io.File;
publicclass MainActivity extendsActivity {
 privateFile fileName = null;
 privateButton button;
 privateImageView imageView;
 @Override
 protectedvoid onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button)findViewById(R.id.button);
  imageView = (ImageView)findViewById(R.id.imageView);
  button.setOnClickListener(newView.OnClickListener() {
   @Override
   publicvoid onClick(View v) {
    File filePath = newFile(Environment.getExternalStorageDirectory(), "myCamera");
    if(!filePath.exists()){
     filePath.mkdirs();
    }
    fileName = newFile(filePath, System.currentTimeMillis() + ".jpg");
    try{
     if(!fileName.exists()){
      fileName.createNewFile();
     }
    }catch(Exception e){
     e.printStackTrace();
    }
    // intent用来启动系统自带的Camera
    Intent intent = newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
    // 将系统Camera的拍摄结果写入到文件
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fileName));
    // 启动intent对应的Activity,返回默认消息
    startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);
   }
  });
 }
 @Override
 protectedvoid onActivityResult(intrequestCode, intresultCode, Intent data){
  if(requestCode == Activity.DEFAULT_KEYS_DIALER){
   // MainActivity接收Camera返回的消息,然后将已经写入的图片显示在ImageView内
   imageView.setImageURI(Uri.fromFile(fileName));
  }
 }
}

2、自己写一个摄像界面

      自己写摄像的界面,主要应用了SurfaceView来显示摄像机的画面。然后通过一个Button来保存当前的画面。

      同样的,我们需要添加camera和SDCard权限:

?
1
2
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>

      首先,我们初始化这个SurfaceView,为这个SurfaceView添加一个对应的Callback即可:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
privateSurfaceView surfaceView;
privateSurfaceHolder.Callback callback;
surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
 callback = newSurfaceHolder.Callback(){
  @Override
  publicvoid surfaceCreated(SurfaceHolder holder) {
   startCamera();// 用于启动摄像头
  }
  @Override
  publicvoid surfaceChanged(SurfaceHolder holder, intformat, intwidth, intheight) {
  }
  @Override
  publicvoid surfaceDestroyed(SurfaceHolder holder) {
   stopCamera();// 用于关闭摄像头
  }
 };
 surfaceView.getHolder().addCallback(callback);// 将Callback绑定到SurfaceView

      在启动摄像头的时候,首先打开摄像头连接,然后将其图像输出到SurfaceView上,然后启动摄像头预览即可在SurfaceView上显示摄像头的画面,这里的画面和实际画面相差有90度,所以我们需要将图像旋转90度之后才可以和拍摄的物体方向一致。

      在关闭摄像头时,只要停止预览,然后释放摄像头资源即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
publicvoid startCamera(){
 camera = Camera.open();
 try{
  camera.setPreviewDisplay(surfaceView.getHolder());
  camera.setDisplayOrientation(90);
  camera.startPreview();
 }catch(IOException e) {
  e.printStackTrace();
 }
}
publicvoid stopCamera(){
 camera.stopPreview();
 camera.release();
 camera = null;
}

      最后,是将拍摄到的图片保存到SDCard,我们单击Button来拍摄图片,调用Camera.takePicture()方法,其原型为:

?
1
2
3
4
5
6
7
8
9
/**
  * Equivalent to takePicture(shutter, raw, null, jpeg).
  *
  * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback)
  */
 publicfinal void takePicture(ShutterCallback shutter, PictureCallback raw,
   PictureCallback jpeg) {
  takePicture(shutter, raw, null, jpeg);
 }

      其中,shutter为按快门瞬间的回调,就是说按快门瞬间会调用ShutterCallback.onShutter()方法。raw是未压缩的图像的回调,即处理图像原始数据的时候会调用PictureCallback.onPictureTaken()方法。jpeg为处理JPEG图片时候的回调,即我们需要将图像数据按照jpg格式保存的时候会调用这个方法,PictureCallback.onPIctureTaken()。这里我们就调用了这个方法,从而将jpg图片存储到SDCard上。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
button.setOnClickListener(newView.OnClickListener() {
  @Override
  publicvoid onClick(View v) {
   camera.takePicture(null,null,newCamera.PictureCallback() {
    @Override
    publicvoid onPictureTaken(byte[] data, Camera camera) {
     try{
      File filePath = newFile(Environment.getExternalStorageDirectory(), "myCamera");
      if(!filePath.exists()) {
       filePath.mkdirs();
      }
      File fileName = newFile(filePath, System.currentTimeMillis() + ".jpg");
      fileName.createNewFile();
      FileOutputStream fos = newFileOutputStream(fileName);
      fos.write(data);
      fos.flush();
      fos.close();
     }catch(IOException e) {
      e.printStackTrace();
     }
    }
   });
  }
 });

      这样,我们便实现了用SurfaceView预览摄像头画面,点击Button将当前预览保存到SDCard中。

完整代码如下:

?
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
importandroid.app.Activity;
importandroid.hardware.Camera;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.view.SurfaceHolder;
importandroid.view.SurfaceView;
importandroid.view.View;
importandroid.widget.Button;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
publicclass MainActivity extendsActivity {
 privateCamera camera;
 privateButton button;
 privateSurfaceView surfaceView;
 privateSurfaceHolder.Callback callback;
 @Override
 protectedvoid onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button)findViewById(R.id.button);
  surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
  callback = newSurfaceHolder.Callback(){
   @Override
   publicvoid surfaceCreated(SurfaceHolder holder) {
    startCamera();
   }
   @Override
   publicvoid surfaceChanged(SurfaceHolder holder, intformat, intwidth, intheight) {
   }
   @Override
   publicvoid surfaceDestroyed(SurfaceHolder holder) {
    stopCamera();
   }
  };
  surfaceView.getHolder().addCallback(callback);
  button.setOnClickListener(newView.OnClickListener() {
   @Override
   publicvoid onClick(View v) {
    camera.takePicture(null,null,newCamera.PictureCallback() {
     @Override
     publicvoid onPictureTaken(byte[] data, Camera camera) {
      try{
       File filePath = newFile(Environment.getExternalStorageDirectory(), "myCamera");
       if(!filePath.exists()) {
        filePath.mkdirs();
       }
       File fileName = newFile(filePath, System.currentTimeMillis() + ".jpg");
       fileName.createNewFile();
       FileOutputStream fos = newFileOutputStream(fileName);
       fos.write(data);
       fos.flush();
       fos.close();
      }catch(IOException e) {
       e.printStackTrace();
      }
     }
    });
   }
  });
 }
 publicvoid startCamera(){
  camera = Camera.open();
  try{
   camera.setPreviewDisplay(surfaceView.getHolder());
   camera.setDisplayOrientation(90);
   camera.startPreview();
  }catch(IOException e) {
   e.printStackTrace();
  }
 }
 publicvoid stopCamera(){
  camera.stopPreview();
  camera.release();
  camera = null;
 }
}

以上所述是本文给大家介绍的关于Android 开发随手笔记之使用摄像头拍照的全部内容,希望大家喜欢。



0 0