Android 无预览拍照功能
最近得到了一个需求,在后台拍照并保存
publicvoidonTakePhotoClicked(){
finalSurfaceViewpreview=newSurfaceView(this);
SurfaceHolderholder=preview.getHolder();
//deprecatedsetting,butrequiredonAndroidversionspriorto3.0
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.addCallback(newSurfaceHolder.Callback(){
@Override
//ThepreviewmusthappenatorafterthispointortakePicturefails
publicvoidsurfaceCreated(SurfaceHolderholder){
Log.d(TAG,"Surfacecreated");
camera=null;
try{
camera=Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
Log.d(TAG,"Openedcamera");
try{
camera.setPreviewDisplay(holder);
}catch(IOExceptione){
thrownewRuntimeException(e);
}
camera.startPreview();
Log.d(TAG,"Startedpreview");
//延时拍照
ThreadUtils.postOnUiThreadDelayed(newRunnable(){
@Override
publicvoidrun(){
Log.e("zgj","开始拍照");
camera.takePicture(null,null,CameraService.this);
}
},5000);
}catch(Exceptione){
if(camera!=null)
camera.release();
thrownewRuntimeException(e);
}
}
@Override
publicvoidsurfaceDestroyed(SurfaceHolderholder){}
@Override
publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,intheight){}
});
WindowManagerwm=(WindowManager)getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParamsparams=newWindowManager.LayoutParams(
1,1,//Mustbeatleast1x1
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
0,
//Don'tknowifthisisasafedefault
PixelFormat.UNKNOWN);
//Don'tsetthepreviewvisibilitytoGONEorINVISIBLE
wm.addView(preview,params);
}
@Override
publicvoidonPictureTaken(byte[]bytes,Cameracamera){
Log.e("zgj","拍照结束");
FilepictureDir=Environment.getExternalStorageDirectory();
if(pictureDir==null){
Log.d("zgj",
"Errorcreatingmediafile,checkstoragepermissions!");
return;
}
try{
StringpictureName="ssss.png";
Filefile=newFile(pictureDir+"/pic/");
if(!file.exists()){
file.mkdir();
}
file=newFile(pictureDir+"/pic/"+pictureName);
FileOutputStreamfos=newFileOutputStream(file);
fos.write(bytes);
fos.close();
}catch(FileNotFoundExceptione){
Log.d("zgj","Filenotfound:"+e.getMessage());
}catch(IOExceptione){
Log.d("zgj","Erroraccessingfile:"+e.getMessage());
}
}
总结
以上所述是小编给大家介绍的Android无预览拍照功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!