Android應(yīng)用中拍照和錄制視頻都需要Surface,所以需要創(chuàng)建在Activiy中存在SurfaceView或者VideoView,可以在xml中配置,在代碼中加載。同時主Activity中需要implements SurfaceHolder.Callback,實現(xiàn)其中的surfaceCreate, surfaceChanged, surfaceDestoryed三個方法。具體流程如下
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比沈陽網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式沈陽網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋沈陽地區(qū)。費用合理售后完善,十年實體公司更值得信賴。
First:
SurfaceView mSurfaceView = (SurfaceView)findViewById(R.id.surfaceview);
SurfaceHolder mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
當(dāng)調(diào)用addCallback的時候,就會觸發(fā)SurfaceHolder.Callback回調(diào),執(zhí)行surfaceCreate方法,可以在surfaceCreate中做一些初始化。
Second:
打開攝像頭,進行初始化。如:
Camera mCamera = Camera.open();
mCamera.setPreviewDisplay(mHolder);
當(dāng)surfaceview被覆蓋或者應(yīng)用結(jié)束退出時,surface會destory,執(zhí)行surfaceDestoryed回調(diào),可以在該回調(diào)中釋放Camera,如:
mCamera.stopPrevew();
mCamera.release();
mCamera = null;
Thrid:
進行拍照時,調(diào)用takePicture接口,傳入callback參數(shù),并在最后一個callback中獲取byte[] data,并將數(shù)據(jù)以jpg文件格式保存,如下所示:
mCamera.takePicture(new ShutterCallback(){}, new PictureCallback(){},new PictureCallback(){}, new PictureCallback(){public void onPictureTaken(byte[] data, Camera camera) {save(data)} });
在save方法中通過流輸出到指定路徑:
File mediaStoragePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "PicFiles");
String fileName = mediaStoragePath.getPath() + File.sperator + "PIC_" + System.currentTimeMills() + ".jpg";
File pictureFile = new File(fileName);
FileOutputStream fos = new FileOutputStream(picture);
fos.write(data);
fos.close();