该类描述
这个类可以完成摄像头的前后摄、拍照预览、并且拍照出来的照片也可以进行旋转包括镜像解决
public class CameraRearWZXActivity extends Activity implements View.OnClickListener {
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
///为了使照片竖直显示
static {
ORIENTATIONS.append(Surface.ROTATION_0, 180);
ORIENTATIONS.append(Surface.ROTATION_90, 180);
ORIENTATIONS.append(Surface.ROTATION_180, 180);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private boolean DoWantToClick =false;
public static String dataState ="0";
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private ImageView iv_show;
private CameraManager mCameraManager;//摄像头管理器
private Handler childHandler, mainHandler;
private String mCameraID;//摄像头Id 0 为后 1 为前
private ImageReader mImageReader;
private CameraCaptureSession mCameraCaptureSession;
private CameraDevice mCameraDevice;
private ImageView take_photo_button;
private RelativeLayout ll_confirm_layout;
private ImageView cancle_save_button,save_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.camera_front_wzx);
initVIew();
}
/**
* 初始化
*/
private void initVIew() {
cancle_save_button = (ImageView) findViewById(R.id.cancle_save_button);
save_button =(ImageView)findViewById(R.id.save_button);
ll_confirm_layout = (RelativeLayout) findViewById(R.id.ll_confirm_layout);
take_photo_button = (ImageView) findViewById(R.id.take_photo_button);
iv_show = (ImageView) findViewById(R.id.iv_show_camera2_activity);
//mSurfaceView
mSurfaceView = (SurfaceView) findViewById(R.id.surface_view_camera2_activity);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.setKeepScreenOn(true);
// mSurfaceView添加回调
mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) { //SurfaceView创建
// 初始化Camera
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
initCamera2();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) { //SurfaceView销毁
// 释放Camera资源
if (null != mCameraDevice) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mCameraDevice.close();
}
CameraRearWZXActivity.this.mCameraDevice = null;
}
}
});
take_photo_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePicture();
take_photo_button.setVisibility(View.GONE);
ll_confirm_layout.setVisibility(View.VISIBLE);
}
});
//这个是fail
cancle_save_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1 = getIntent();
if(intent1.getStringExtra("infoType").equals("auto")){
if (FactoryDefaultData.GetData("overalldata")==null){
}else {
String Overalldata =FactoryDefaultData.GetData("overalldata");
Log.d("wzx11111111111111","Overalldata"+FactoryDefaultData.GetData("overalldata"));
char[] temp = Overalldata.toCharArray();
temp[12] = '2';
FactoryDefaultData.SetData("overalldata",String.valueOf(temp));
openNextActivity();
Log.d("wzx11111111111111","========="+FactoryDefaultData.GetData("overalldata"));
}
}else {
if (FactoryDefaultData.GetData("overalldata")==null){
}else {
String Overalldata =FactoryDefaultData.GetData("overalldata");
Log.d("wzx11111111111111","Overalldata"+FactoryDefaultData.GetData("overalldata"));
char[] temp = Overalldata.toCharArray();
temp[12] = '2';
FactoryDefaultData.SetData("overalldata",String.valueOf(temp));
DoWantToClick =true;
dataState="2";
Log.d("wzx11111111111111","========="+FactoryDefaultData.GetData("overalldata"));
}
}
SaveResult.save(getApplicationContext(), "rearcamera", false);
finish();
}
});
save_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = getIntent();
if(intent2.getStringExtra("infoType").equals("auto")){
if (FactoryDefaultData.GetData("overalldata")==null){
}else {
String Overalldata =FactoryDefaultData.GetData("overalldata");
Log.d("wzx11111111111111","Overalldata"+FactoryDefaultData.GetData("overalldata"));
char[] temp = Overalldata.toCharArray();
temp[12] = '1';
FactoryDefaultData.SetData("overalldata",String.valueOf(temp));
openNextActivity();
Log.d("wzx11111111111111","========="+FactoryDefaultData.GetData("overalldata"));
}
}else {
if (FactoryDefaultData.GetData("overalldata")==null){
}else {
String Overalldata =FactoryDefaultData.GetData("overalldata");
Log.d("wzx11111111111111","Overalldata"+FactoryDefaultData.GetData("overalldata"));
char[] temp = Overalldata.toCharArray();
temp[12] = '1';
FactoryDefaultData.SetData("overalldata",String.valueOf(temp));
DoWantToClick = true;
dataState = "1";
Log.d("wzx11111111111111","========="+FactoryDefaultData.GetData("overalldata"));
}
}
SaveResult.save(getApplicationContext(), "rearcamera", true);
finish();
}
});
}
//这个是要跳转
private void openNextActivity(){
Intent app_intent = new Intent(CameraRearWZXActivity.this, BatteryActivity.class);
app_intent.putExtra("infoType", "auto");
startActivity(app_intent);
finish();
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
Log.e("MainActivity","dispatchKeyEvent:keyCode--"+event.getKeyCode());
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_MENU|| event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
//拦截到home和back键然后做相应的功能
Log.d("111111111111111111", "KEYCODE_BACK KEYCODE_HOME: 111111");
if (DoWantToClick){
finish();
}else {
}
// finish();
return true;
} else {
return super.dispatchKeyEvent(event);
}
}
/**
* 初始化Camera2
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera2() {
HandlerThread handlerThread = new HandlerThread("Camera2");
handlerThread.start();
childHandler = new Handler(handlerThread.getLooper());
mainHandler = new Handler(getMainLooper());
// mCameraID = "" + CameraCharacteristics.LENS_FACING_BACK;//后摄像头
mCameraID = "" + CameraCharacteristics.LENS_FACING_FRONT;//前摄像头
mImageReader = ImageReader.newInstance(1080, 1920, ImageFormat.JPEG,1);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() { //可以在这里处理拍照得到的临时照片 例如,写入本地
@Override
public void onImageAvailable(ImageReader reader) {
mCameraDevice.close();
mSurfaceView.setVisibility(View.GONE);
iv_show.setVisibility(View.VISIBLE);
// 拿到拍照照片数据
Image image = reader.acquireNextImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);//由缓冲区存入字节数组
final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if (bitmap != null) {
Matrix matrix = new Matrix();
// matrix.postRotate(0); 这个是后摄
matrix.postRotate(90); //这个是前摄
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
iv_show.setImageBitmap(rotatedBitmap);
}
}
}, mainHandler);
//获取摄像头管理
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
//打开摄像头
mCameraManager.openCamera(mCameraID, stateCallback, mainHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* 摄像头创建监听
*/
private CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {//打开摄像头
mCameraDevice = camera;
//开启预览
takePreview();
}
@Override
public void onDisconnected(CameraDevice camera) {//关闭摄像头
if (null != mCameraDevice) {
mCameraDevice.close();
CameraRearWZXActivity.this.mCameraDevice = null;
}
}
@Override
public void onError(CameraDevice camera, int error) {//发生错误
Toast.makeText(CameraRearWZXActivity.this, "摄像头开启失败", Toast.LENGTH_SHORT).show();
}
};
/**
* 开始预览
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void takePreview() {
try {
// 创建预览需要的CaptureRequest.Builder
final CaptureRequest.Builder previewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
// 将SurfaceView的surface作为CaptureRequest.Builder的目标
previewRequestBuilder.addTarget(mSurfaceHolder.getSurface());
// 创建CameraCaptureSession,该对象负责管理处理预览请求和拍照请求
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mCameraDevice.createCaptureSession(Arrays.asList(mSurfaceHolder.getSurface(), mImageReader.getSurface()), new CameraCaptureSession.StateCallback() // ③
{
@Override
public void onConfigured(CameraCaptureSession cameraCaptureSession) {
if (null == mCameraDevice) return;
// 当摄像头已经准备好时,开始显示预览
mCameraCaptureSession = cameraCaptureSession;
try {
// 自动对焦
previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// 打开闪光灯
previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
// 显示预览
CaptureRequest previewRequest = previewRequestBuilder.build();
mCameraCaptureSession.setRepeatingRequest(previewRequest, null, childHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
Toast.makeText(CameraRearWZXActivity.this, "配置失败", Toast.LENGTH_SHORT).show();
}
}, childHandler);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* 点击事件
*/
@Override
public void onClick(View v) {
// takePicture();
}
/**
* 拍照
*/
private void takePicture() {
if (mCameraDevice == null) return;
// 创建拍照需要的CaptureRequest.Builder
final CaptureRequest.Builder captureRequestBuilder;
try {
captureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
// 将imageReader的surface作为CaptureRequest.Builder的目标
captureRequestBuilder.addTarget(mImageReader.getSurface());
// 自动对焦
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// 自动曝光
captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
// 获取手机方向
// CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
// int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
// int deviceOrientation = ORIENTATIONS.get(rotation);
// int rotation = getWindowManager().getDefaultDisplay().getRotation();
int rotation =360;
Log.d("wzx1111", "takePicture: "+rotation);
// 根据设备方向计算设置照片的方向
captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
//拍照
CaptureRequest mCaptureRequest = captureRequestBuilder.build();
mCameraCaptureSession.capture(mCaptureRequest, null, childHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}