1.camer调用需要在AndroidManifest.xml中添加申请相机权限
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
一、预览activity代码
package com.bw.test;
import android.annotation.TargetApi;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback {
private SurfaceView surfaceView;
private Camera.Parameters parameters;
private int formatType;
private int width=1920;
private int height=1080;
private int framerate=24;
private SurfaceHolder surfaceHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Camera camera = getBackCamera();
startcamera(camera);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private void startcamera(Camera mCamera){
if(mCamera != null){
try {
mCamera.setPreviewCallback(this);
//mCamera.setDisplayOrientation(90);
if(parameters == null){
parameters = mCamera.getParameters();
}
getPreviewFormats(parameters);
parameters.setPreviewFormat(formatType);//设置输出的YUV数据格式
parameters.setPreviewSize(width, height);//设置预览画面分辨率,需要相机支持
parameters.setPreviewFpsRange(framerate*1000,framerate*1000);//设置的帧率需要相机支持,否则会报错
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);//设置自动聚焦
mCamera.setParameters(parameters);
mCamera.setPreviewDisplay(surfaceHolder);//设置相机画面预览渲染窗口
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取设备支持的预览帧画面格式
* @param parameters
*/
private void getPreviewFormats(Camera.Parameters parameters) {
List<Integer> previewFormatsSizes = parameters.getSupportedPreviewFormats();
if( -1 != previewFormatsSizes.indexOf(ImageFormat.YV12))
{
formatType = ImageFormat.YV12;
}
else if(-1 != previewFormatsSizes.indexOf(ImageFormat.NV21))
{
formatType = ImageFormat.NV21;
}
else
{
formatType = -1;
return ;
}
}
@TargetApi(9)
private Camera getBackCamera() {
Camera c = null;
try {
c = Camera.open(0); // attempt to get a Camera instance
} catch (Exception e) {
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
//TODO data就为YUV数据
}
}
获取到相机回调的YUV数据后就可以对其进行编码操作。