android camera
布局 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/content_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="40dp" android:paddingLeft="0dp" android:paddingRight="0dp" android:paddingTop="0dp" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.admin.smartcam.main.MainActivity" tools:showIn="@layout/app_bar_main"> <FrameLayout android:id="@+id/camera_FrameLayout" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> </RelativeLayout>
1、在android4.0以下的版本支持【 android.hardware.Camera】api
2、其使用很简单
代码如下:
这个类用于返回一个camera package com.admin.smartcam.androidcamera.camera; /** * Created by Admin on 2017/4/27 0027. * android4.0以下版本使用 */ public class MinForCamera { private static int cameraBackOrFront = 0; private MinForCamera() { } public void setCamera(int cameraBackOrFront) { this.cameraBackOrFront = cameraBackOrFront; } private static android.hardware.Camera camera = android.hardware.Camera.open(cameraBackOrFront); // attempt to get a Camera instance public static android.hardware.Camera getCamera() { return camera; // returns null if camera is unavailable } }
在MainActivity.java中调用: public void initScreen() { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏 getWindow().setFormat(PixelFormat.TRANSLUCENT); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//设置高亮 } @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void startView() { if (checkCameraHardware(this) == true) { //检测相机硬件 final Camera mCamera = MinForCamera.getCamera();//获得系统摄像机 showCamera = new ShowCamera(MainActivity.this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_FrameLayout); preview.addView(showCamera); } } /** * 检查摄像机是否可用 * * @param context * @return */ private boolean checkCameraHardware(Context context) { if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) { // this device has a camera return true; } else { // no camera on this device return false; } }
我使用的是SurfaceView作为显示载体 package com.admin.smartcam.androidcamera.camera; import android.content.Context; import android.graphics.Paint; import android.graphics.PixelFormat; import android.hardware.Camera; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Toast; import java.lang.reflect.Method; import java.util.Objects; import java.util.Timer; import java.util.TimerTask; /** * 自定义相机显示 * Created by Admin on 2017/1/31. */ @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback, Camera.AutoFocusCallback, View.OnClickListener, Camera.FaceDetectionListener { private SurfaceHolder hold; private Camera theCamera; private Context context; private Paint paint = null; Camera.Parameters parameters; @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH) public ShowCamera(Context context, Camera camera) { super(context); this.theCamera = camera; this.context = context; if (cameranumber() <= 0) //没有可用相机 { Toast.makeText(context, "未检测到可用相机", Toast.LENGTH_SHORT).show(); } else { // videoMed = new VideoMed(); //录制视屏 hold = getHolder(); hold.addCallback(this); hold.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } } /** * 返回所有可用相机总数 * @return */ public int cameranumber() { return theCamera.getNumberOfCameras();//得到所有可用相机的总数 } @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { if (Integer.parseInt(Build.VERSION.SDK) >= 15) { initCamera(); //相机参数的初始化设置 hold.addCallback(this); // holder加入回调接口 // setType必须设置,要不出错. hold.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); TimerTask task = new TimerTask() { @Override public void run() { //videoMed.StopWriteVideo(); } }; Timer timer = new Timer(); timer.scheduleAtFixedRate(task, 0, 1000); } else { setDispaly(parameters, theCamera); //控制图像正常显示 theCamera.cancelAutoFocus(); //如果要实现连续的自动对焦,这一句必须加上 } } /** * 预览发生改变 * * @param surfaceHolder * @param i * @param i1 * @param i2 */ @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { if (surfaceHolder.getSurface() == null) { // 预览不存在 return; } // stop preview before making changes try { if (parameters.getMaxNumDetectedFaces() > 0) //检测设备是否支持人脸识别 { theCamera.stopFaceDetection(); } theCamera.stopPreview(); //theCamera.setPreviewCallback(null); //theCamera.release();//释放资源 } catch (Exception e) { Log.d("<<<相机改变>>>", "调整出错!+"+i+">>i1<<"+i1+">>12<<"+i2); } // 在这里做任何调整,旋转或重新格式化变化 try { theCamera.setPreviewDisplay(surfaceHolder); surfaceHolder.setFixedSize(i,i1); theCamera.startPreview(); //设置人脸识别监听 if (parameters.getMaxNumDetectedFaces() > 0) { //检测设备是否支持人脸识别 Log.d("启动人脸检测》》","正在启动!"); theCamera.startFaceDetection();//启动人脸检测相机需要在startPreview()之后 theCamera.setFaceDetectionListener(ShowCamera.this); } } catch (Exception e) { Log.d("相机改变:>>", "相机改变,调整出错!"+i+">>i1<<"+i1+">>12<<"+i2); } } /** * 预览结束,关闭相应资源 * @param surfaceHolder */ @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { if (theCamera != null) { try { Log.d("相机销毁:>>", "相机销毁!"+theCamera); //parameters.notify(); theCamera.stopFaceDetection(); //theCamera.setPreviewCallback(null); theCamera.stopPreview(); //theCamera.setPreviewCallbackWithBuffer(null); theCamera.release(); theCamera = null; Log.d("相机销毁:>>", "相机销毁成功!"+theCamera); } catch (Exception e) { e.printStackTrace(); } } } /** * 实现自动对焦 * * @param b * @param camera */ @Override public void onAutoFocus(boolean b, Camera camera) { if (b) { camera.cancelAutoFocus();//自动对焦。 } } //相机参数的初始化设置 @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void initCamera() { if (theCamera != null) { Log.d("初始化相机","相机:"+theCamera); parameters = theCamera.getParameters(); parameters.setPictureFormat(PixelFormat.JPEG); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); //不开启闪光灯 FLASH_MODE_ON//开启闪光灯 parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦 theCamera.setParameters(parameters); setDispaly(parameters, theCamera); theCamera.cancelAutoFocus();//如果要实现连续的自动对焦,这一句必须加上 //设置人脸识别监听 if (parameters.getMaxNumDetectedFaces() > 0) synchronized (Objects.class){ //检测设备是否支持人脸识别 theCamera.startPreview(); Log.d("启动人脸检测》》","正在启动!"); //theCamera.startFaceDetection();//启动人脸检测相机需要在startPreview()之后 //theCamera.setFaceDetectionListener(ShowCamera.this); } else //Toast.makeText(context, "你的设备不支持人脸识别", Toast.LENGTH_SHORT).show(); theCamera.startPreview(); } } //控制图像的正确显示方向 private void setDispaly(Camera.Parameters parameters, Camera camera) { if (Integer.parseInt(Build.VERSION.SDK) >= 8) { setDisplayOrientation(camera, 90); } else { parameters.setRotation(90); } } //实现的图像的正确显示 private void setDisplayOrientation(Camera camera, int i) { Method downPolymorphic; try { downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[]{int.class}); if (downPolymorphic != null) { downPolymorphic.invoke(camera, new Object[]{i}); } } catch (Exception e) { Log.e("图像出错+Camera:", "图像出错!"); } } @Override public void onClick(View view) { if (view != null) { Toast.makeText(context, "单击事件" + view, Toast.LENGTH_SHORT).show(); } } @Override public void onFaceDetection(Camera.Face[] faces, Camera camera) { if (faces.length > 0) { for (Camera.Face face : faces) { { Log.d("人脸", "检测到人脸坐标为: " + face.rect.centerX() * 1.1f + "\n 检测到人脸坐标为:Y : " + face.rect.centerY() * 1.1f); } } // // VideoMed video = new VideoMed();//录制视屏 // video.StopWriteVideo(); // new EmailToUser("1928654615@qq.com", "主人:检测到监控范围内有人出现!").start(); } } private void timeTack() { Log.d("启动人脸检测》》","正在启动*******!"); new Runnable() { @Override public void run() { try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } Log.d("启动人脸检测》》","正在启动!"); theCamera.startFaceDetection();//启动人脸检测相机需要在startPreview()之后 theCamera.setFaceDetectionListener(ShowCamera.this); Log.d("启动人脸检测》》","启动成功!"); } }.run(); //ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); //service.scheduleAtFixedRate(runnable,2,0, TimeUnit.SECONDS); } private void facetimeTack() { TimerTask task = new TimerTask() { @Override public void run() { try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } theCamera.startFaceDetection();//启动人脸检测相机需要在startPreview()之后 theCamera.setFaceDetectionListener(ShowCamera.this); } }; //new Timer().scheduleAtFixedRate(task,1500,5000000); } }
记得加权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
用自己所知道的去帮助他人,就像别人当初帮助自己一样!