现在的手机几乎都实现照相机功能了,而且在硬件的支持下像素也越来越高,在现实生活中的用途也越来越广,而在Android中专门 提供了Camera来处理相机相关的事件,Camera 是一个专门用来连接和断开相机服务的类,Camera 下面包括如下几个事件:

Camera.AutoFocusCallback: 自动调焦功能;
Camera.ErrorCallback:错误信息捕捉;
Camera.Parameters :相机的属性参数
Camera.PictureCallback:拍照、产生图片时触发;
Camera.PreviewCallback:相机预览设置;
Camera.ShutterCallback:快门设置;
Camera.Size:图片尺寸;

要在Android中使用相机服务很简单,Camera没有构造方法,我们要使用它直接通过open()方法来打开相机设备,然后通过 Camera.Parameters 对相机的一些属性进行设置,比如输出图片的格式、大小等等。下面是Camera类一些常用的方法介绍。

Camera类的方法
方法 说明
autoFocus 设置自动对焦
getParameters 得到相机的参数
open 启动相机服务
release 释放Camera服务
setPreviewDisplay 设置预览
setParameters 设置预览参数
startPreview 开始预览
stopPreview 停止预览
takePicture 拍照

这里重点说明一下拍照的方法和使用, takePicture 方法要实现3个回调函数,分别是: Camera.ShutterCallback (快门) 和 两个Camera.PictureCallback(图像数据)。这里我们在拍照之后要取得图像数据就需要实现Camera.PictureCallback 的 onPictureTaken 方法。onPictureTaken 中第一个参数就是图像数据, 第二个参数则是相机。
下面是一个相机拍照的例子。相机需要一个界面来预览当前拍摄的效果,这里可以使用SurfaceView类。 我们先来看看在模拟器上的运行效果吧。

[img]http://disanji.net/wp-content/uploads/2011/01/20110116_523e2e9f_1d86_3e83_8b70_a11243a317fe.jpg[/img]

下面我们来看具体如何使用相机服务预览效果,最后按导航键中键来拍照,将照片保存到SD卡中(当然首先要确认有SD卡插入)。 代码如下

package xiaohang.zhimeng;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;

public class Activity01 extends Activity {

	private Preview mPreview;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Create our Preview view and set it as the content of our activity.
        mPreview = new Preview(this);
        setContentView(mPreview);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event){
    	switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
			mPreview.takePicture();
			break;
		}
    	return true;
    }
}  
    /*Preview-显示Preview*/
    class Preview extends SurfaceView implements SurfaceHolder.Callback{

    	SurfaceHolder mHolder;
    	Camera mCamera;
    	Bitmap cameraBitmap;

		public Preview(Context context) {
			super(context);
			//得到SurfaceHolder对象
			mHolder = getHolder();
			//添加回调函数
			mHolder.addCallback(this);
			//设置SurfaceHolder 的类型
			mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}

		//在Surface的大小发生改变时激发
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			/*构建Camera.Parameters对相机的参数进行设置*/
			Camera.Parameters parameters = mCamera.getParameters();
			/*设置拍照的图片格式*/
			parameters.setPictureFormat(PixelFormat.JPEG);
			/*设置Preview(预览)的尺寸*/
			parameters.setPreviewSize(320, 480);
			mCamera.setParameters(parameters);
			/*开始预览*/
			mCamera.startPreview();
		}

		/*拍照片*/
		public void takePicture(){
			if (mCamera != null) {
				mCamera.takePicture(null, null, jpegCallback);
			}
		}
		/*拍照后输出图片*/
		private PictureCallback jpegCallback = new PictureCallback(){

			@Override
			public void onPictureTaken(byte[] data, Camera camera) {
				// TODO Handle JPEG image data
				//解码一个不可变的位图 从指定的字节数组
				cameraBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				File myCaptureFile = new File("/sdcard/camera1.jpg");
				try {
					BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
					//压缩位图到指定的OutputStream
					cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
					//刷新此缓冲区的输出流
					bos.flush();
					//关闭此输出流并释放与此流有关的所有系统资源
					bos.close();
					/*将拍到的图片绘制出来*/
					//锁定画布
					Canvas canvas = mHolder.lockCanvas();
					canvas.drawBitmap(cameraBitmap, 0, 0, null);
					//绘制后解锁,绘制后必须解锁才能显示
					mHolder.unlockCanvasAndPost(canvas);
				} catch (Exception e) {
					e.getMessage();
				}
			}
		};

		//在创建Surface时激发
		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			/*启动Camera*/
			mCamera = Camera.open();
			try {
				mCamera.setPreviewDisplay(holder);
			} catch (Exception e) {
				/*释放mCamera*/
				mCamera.release();
				mCamera = null;
			}
		}       

		//在销毁Surface时激发
		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			/*停止预览*/
			mCamera.stopPreview();
			mCamera = null;
		}
    }




最后大家不要忘记了加上权限声明


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





[size=large][b]Android Camera照相机[/b][/size]



package com.Aina.Android;  

import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  

import android.content.Context;  
import android.graphics.Bitmap;  
import android.graphics.BitmapFactory;  
import android.graphics.Canvas;  
import android.graphics.PixelFormat;  
import android.hardware.Camera;  
import android.util.Log;  
import android.view.KeyEvent;  
import android.view.SurfaceHolder;  
import android.view.SurfaceView;  

/** 
 * com.Aina.Android Pro_Camera 
 *  
 * @author Aina.huang E-mail: 674023920@qq.com 
 * @version 创建时间:2010 Jul 7, 2010 2:50:15 PM 类说明 
 */  
public class PreView extends SurfaceView implements SurfaceHolder.Callback {  

    private SurfaceHolder holder = null;  
    private Camera mCamera = null;  
    private Bitmap mBitmap = null;  

    public PreView(Context context) {  
        super(context);  
        Log.i("TAG", "PreView()");  
        // TODO Auto-generated constructor stub  
        holder = this.getHolder();  
        holder.addCallback(this);  
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
    }  

    public void surfaceChanged(SurfaceHolder holder, int format, int width,  
            int height) {  
        Log.i("TAG", "surfaceChanged");  
        // TODO Auto-generated method stub  
        Camera.Parameters parameters = mCamera.getParameters();  
        parameters.setPictureFormat(PixelFormat.JPEG);//设置图片格式  
        parameters.setPreviewSize(320, 480);//设置尺寸  
//      parameters.setPictureSize(320, 480);//设置分辨率  
        mCamera.setParameters(parameters);  
        mCamera.startPreview();//开始预览  
    }  

    public void surfaceCreated(SurfaceHolder holder) {  
        Log.i("TAG", "surfaceCreated");  
        // TODO Auto-generated method stub  
        mCamera = Camera.open();//启动服务  
        try {  
            mCamera.setPreviewDisplay(holder);//设置预览  
        } catch (IOException e) {  
            mCamera.release();//释放  
            mCamera = null;  
        }  
    }  

    public void surfaceDestroyed(SurfaceHolder holder) {  
        Log.i("TAG", "surfaceDestroyed");  
        // TODO Auto-generated method stub  
        mCamera.stopPreview();//停止预览  
        mCamera = null;  
    }  

    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if(keyCode==KeyEvent.KEYCODE_DPAD_CENTER){  
            if(mCamera !=null){  
                mCamera.takePicture(null, null,pic);  
            }  
        }  
        return super.onKeyDown(keyCode, event);  
    }  
    //拍照后输出图片  
    public Camera.PictureCallback pic = new Camera.PictureCallback(){  

        public void onPictureTaken(byte[] data, Camera camera) {  
            // TODO Auto-generated method stub  
            mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
            File f = new File(android.os.Environment.getExternalStorageDirectory()+"/camera1.jpg");  
            try {  
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(f));  
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, os);  
                os.flush();  
                os.close();  
                Canvas canvas = holder.lockCanvas();  
                canvas.drawBitmap(mBitmap, 0, 0, null);  
                holder.unlockCanvasAndPost(canvas);  
            } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  

    };  
}




package com.Aina.Android;  

import android.app.Activity;  
import android.os.Bundle;  
import android.view.KeyEvent;  
import android.view.Window;  

public class Test extends Activity {  
    /** Called when the activity is first created. */  
    private PreView pv = null;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
        pv = new PreView(this);  
        setContentView(pv);  
    }  

    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        // TODO Auto-generated method stub  
        return pv.onKeyDown(keyCode, event);  
    }  

}




<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
      package="com.Aina.Android"  
      android:versionCode="1"  
      android:versionName="1.0">  
    <application android:icon="@drawable/icon" android:label="@string/app_name">  
        <activity android:name=".Test"  
                  android:label="@string/app_name">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  

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

</manifest>