protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextureView textureView=(TextureView)findViewById(R.id.textureView);
camera2Wrapper=new Camera2Wrapper(this,textureView);
}
@Overrideprotected void onPause() {
// TODO Auto-generated method stub super.onPause();
camera2Wrapper.closeCameraDevice();
}
//Camera2Wrapper.java
package com.xchat.stevenzack.spycamera;
/** * Created by steven on 17-6-15. */import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.content.Context.CONTEXT_INCLUDE_CODE;
/** * Created by steven on 17-6-15. */
public class Camera2Wrapper {
private final static String TAG = "Camera2testJ";
private TextureView mTextureView;
private CameraDevice mCameraDevice;
private CaptureRequest.Builder mPreviewBuilder;
private CameraCaptureSession mPreviewSession;
private Size mPreviewSize;
private int cameraFacing;
private Context context;
private Handler mbackgroundHandler;
public Camera2Wrapper(Context context,TextureView textureView,int cameraID){
this.context=context;
mTextureView=textureView;
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
cameraFacing=cameraID;
}
public void openCamera(int i) {
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
Log.e(TAG, "openCamera E");
int[] faingMap=new int[]{CameraCharacteristics.LENS_FACING_BACK,CameraCharacteristics.LENS_FACING_FRONT};
try {
String mCameraId=manager.getCameraIdList()[0];
for(final String cameraId : manager.getCameraIdList()){
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
if(cOrientation == faingMap[i]) mCameraId= cameraId;
}
CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mPreviewSize = map.getOutputSizes(SurfaceTexture.class)[0];
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.openCamera(mCameraId, mStateCallback, null);
} catch (CameraAccessException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
Log.e(TAG, "openCamera X");
}
private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener(){
@Override public void onSurfaceTextureAvailable(SurfaceTexture surface,
int width, int height) {
// TODO Auto-generated method stub Log.e(TAG, "onSurfaceTextureAvailable, width="+width+",height="+height);
openCamera(cameraFacing);
}
@Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface,
int width, int height) {
// TODO Auto-generated method stub Log.e(TAG, "onSurfaceTextureSizeChanged");
}
@Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
// TODO Auto-generated method stub return false;
}
@Override public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// TODO Auto-generated method stub Log.e(TAG, "onSurfaceTextureUpdated");
}
};
private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override public void onOpened(CameraDevice camera) {
// TODO Auto-generated method stub Log.e(TAG, "onOpened");
mCameraDevice = camera;
startPreview();
}
@Override public void onDisconnected(CameraDevice camera) {
// TODO Auto-generated method stub Log.e(TAG, "onDisconnected");
}
@Override public void onError(CameraDevice camera, int error) {
// TODO Auto-generated method stub Log.e(TAG, "onError");
}
};
private void startPreview() {
// TODO Auto-generated method stub if(null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
Log.e(TAG, "startPreview fail, return");
}
SurfaceTexture texture = mTextureView.getSurfaceTexture();
if(null == texture) {
Log.e(TAG,"texture is null, return");
return;
}
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
Surface surface = new Surface(texture);
try {
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
} catch (CameraAccessException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
mPreviewBuilder.addTarget(surface);
try {
mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override public void onConfigured(CameraCaptureSession session) {
// TODO Auto-generated method stub mPreviewSession = session;
updatePreview();
}
@Override public void onConfigureFailed(CameraCaptureSession session) {
// TODO Auto-generated method stub Toast.makeText(context, "onConfigureFailed", Toast.LENGTH_LONG).show();
}
}, null);
} catch (CameraAccessException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
}
private void updatePreview() {
// TODO Auto-generated method stub if(null == mCameraDevice) {
Log.e(TAG, "updatePreview error, return");
}
mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
HandlerThread thread = new HandlerThread("CameraPreview");
thread.start();
mbackgroundHandler = new Handler(thread.getLooper());
try {
mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mbackgroundHandler);
} catch (CameraAccessException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
}
public void closeCameraDevice(){
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
}
protected void takePictureAndSaveIt(String storagePath, int mRotaion, final CameraCaptureSession.CaptureCallback captureListener) {
if(null == mCameraDevice) {
Log.e(TAG, "cameraDevice is null");
return;
}
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null) {
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
}
int width = 640;
int height = 480;
if (jpegSizes != null && 0 < jpegSizes.length) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurfaces = new ArrayList<Surface>(2);
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
// Orientation captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, mRotaion);
final File file = new File(storagePath);
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
@Override public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(bytes);
output.flush();
} finally {
if (null != output) {
output.close();
}
}
}
};
reader.setOnImageAvailableListener(readerListener,mbackgroundHandler );
mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
@Override public void onConfigured(CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mbackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override public void onConfigureFailed(CameraCaptureSession session) {
}
}, mbackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
protected void takePicture(int mRotaion, final onBitmapGetListener onBitmapGetListener ) {
if(null == mCameraDevice) {
Log.e(TAG, "cameraDevice is null");
return;
}
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null) {
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
}
int width = 640;
int height = 480;
if (jpegSizes != null && 0 < jpegSizes.length) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurfaces = new ArrayList<Surface>(2);
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
// Orientation captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, mRotaion);
final Bitmap[] bitmap=new Bitmap[1];
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
@Override public void onImageAvailable(ImageReader reader) {
Image image = null;
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
bitmap[0]=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
image.close();
}
};
reader.setOnImageAvailableListener(readerListener,mbackgroundHandler );
final CameraCaptureSession.CaptureCallback captureListener =new CameraCaptureSession.CaptureCallback() {
@Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
onBitmapGetListener.onBitmapGet(bitmap[0]);
}
};
mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
@Override public void onConfigured(CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mbackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override public void onConfigureFailed(CameraCaptureSession session) {
}
}, mbackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
public interface onBitmapGetListener{
void onBitmapGet(Bitmap bitmap);
}
private String getFrontFacingCameraId(CameraManager cManager) throws CameraAccessException {
for(final String cameraId : cManager.getCameraIdList()){
CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId);
int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
if(cOrientation == CameraCharacteristics.LENS_FACING_FRONT) return cameraId;
}
return null;
}
private String getBackFacingCameraId(CameraManager cManager) throws CameraAccessException {
for(final String cameraId : cManager.getCameraIdList()){
CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId);
int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
if(cOrientation == CameraCharacteristics.LENS_FACING_BACK) return cameraId;
}
return null;
}
}
评论
发表评论