1.布局中只有一个SurfaceView和Button,初始SurfaceView通过surface.getHolder获得SurfaceHolder类
SurfaceView sfv= (SurfaceView) findViewById(R.id.surfaceView); holder = sfv.getHolder(); //指定类型 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //指定回调接口 holder.addCallback(new A());
2.回调接口。这里setPictureSize(width,height)宽高并不能随意设置,必须属于
myParameters.getSupportedPictureSizes()
中的,在该回调中并设置了
cam.autoFocus(mAutoFocusCallback);
实现cam的聚焦功能。
myParameters.set("jpeg-quality", 10);这里设置的10使得图片最终质量较差。
private class A implements SurfaceHolder.Callback { @Override public void surfaceCreated(SurfaceHolder holder) { if(cam!=null){ cam.release(); } cam = Camera.open(0); try { myParameters = cam.getParameters(); myParameters.setPictureSize(myParameters.getSupportedPictureSizes().get(0).width,myParameters.getSupportedPictureSizes().get(0).height); for(int i=0;i<myParameters.getSupportedPictureSizes().size();i++){ Log.d(TAG, "surfaceCreated: "+myParameters.getSupportedPictureSizes().get(i).width+"height:"+myParameters.getSupportedPictureSizes().get(i).height); } myParameters.setFocusMode("auto"); myParameters.set("jpeg-quality", 10); cam.setParameters(myParameters); cam.setPreviewDisplay(holder); cam.setDisplayOrientation(90); cam.startPreview(); cam.autoFocus(mAutoFocusCallback); } catch (Exception e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }
3.cam.autoFocus(mAutoFocusCallback)中的回调
private Camera.AutoFocusCallback mAutoFocusCallback=new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { } };
4.在Button点击事件中实现拍照响应
cam.takePicture(null,null,null,new B());
5.B回调,压缩图片,并保存
private class B implements Camera.PictureCallback { @Override public void onPictureTaken(byte[] data, Camera camera) { try { Bitmap a= BitmapFactory.decodeByteArray(data,0,data.length); String fileAdress=Environment.getExternalStorageDirectory()+File.separator+"AA"+File.separator+photoFileName; FileOutputStream out=new FileOutputStream(new File(fileAdress)); //压缩 a.compress(Bitmap.CompressFormat.JPEG,100,out); Toast.makeText(PhotoActivity.this,"",Toast.LENGTH_SHORT).show(); if(cam!=null){ cam.release(); } finish(); } catch (Exception e) { e.printStackTrace(); } } }
6.给surfaceView加上点击事件,点击时,开启聚焦
sfv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { cam.autoFocus(mAutoFocusCallback); return false; } });