Android使用camera2扫码并打开闪光灯代码
时间: 2024-03-10 17:43:49 浏览: 120
Android中编写简单的手电筒小应用的实例教程
下面是一个使用 camera2 API 实现扫码并打开闪光灯的示例代码:
```
public class ScanActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final String TAG = "ScanActivity";
private static final int REQUEST_CAMERA_PERMISSION = 1;
private CameraManager mCameraManager;
private CameraDevice mCameraDevice;
private SurfaceView mSurfaceView;
private ImageReader mImageReader;
private CaptureRequest.Builder mPreviewRequestBuilder;
private CaptureRequest mPreviewRequest;
private HandlerThread mBackgroundThread;
private Handler mBackgroundHandler;
private boolean mFlashSupported;
private boolean mFlashEnabled;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mSurfaceView = findViewById(R.id.surface_view);
mSurfaceView.getHolder().addCallback(this);
}
@Override
protected void onResume() {
super.onResume();
startBackgroundThread();
if (mSurfaceView.isAvailable()) {
openCamera(mSurfaceView.getWidth(), mSurfaceView.getHeight());
} else {
mSurfaceView.getHolder().addCallback(this);
}
}
@Override
protected void onPause() {
closeCamera();
stopBackgroundThread();
super.onPause();
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread(TAG);
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
Log.e(TAG, "stopBackgroundThread: ", e);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private void openCamera(int width, int height) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
String cameraId = mCameraManager.getCameraIdList()[0];
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mImageReader = ImageReader.newInstance(width, height, ImageFormat.YUV_420_888, 2);
mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
if (map == null) {
throw new RuntimeException("Cannot get available preview/video sizes");
}
Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.YUV_420_888)), new CompareSizesByArea());
configureTransform(width, height);
mCameraManager.openCamera(cameraId, mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
Log.e(TAG, "openCamera: ", e);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mImageReader) {
mImageReader.close();
mImageReader = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
} finally {
mCameraOpenCloseLock.release();
}
}
private void configureTransform(int viewWidth, int viewHeight) {
if (null == mSurfaceView || null == mPreviewRequestBuilder) {
return;
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mImageReader.getHeight(), mImageReader.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max((float) viewHeight / mImageReader.getHeight(), (float) viewWidth / mImageReader.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180, centerX, centerY);
}
mSurfaceView.setTransform(matrix);
}
private void createCameraPreviewSession() {
try {
Surface surface = mSurfaceView.getHolder().getSurface();
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
if (null == mCameraDevice) {
return;
}
try {
mPreviewRequest = mPreviewRequestBuilder.build();
cameraCaptureSession.setRepeatingRequest(mPreviewRequest, null, mBackgroundHandler);
} catch (CameraAccessException e) {
Log.e(TAG, "onConfigured: ", e);
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Log.e(TAG, "onConfigureFailed: ");
}
}, null);
} catch (CameraAccessException e) {
Log.e(TAG, "createCameraPreviewSession: ", e);
}
}
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
createCameraPreviewSession();
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
finish();
}
};
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireLatestImage();
if (image == null) {
return;
}
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
int width = image.getWidth();
int height = image.getHeight();
int format = image.getFormat();
int stride = image.getPlanes()[0].getRowStride();
boolean success = false;
if (format == ImageFormat.YUV_420_888) {
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, width, height, stride, 0, 0, width, height, false);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
try {
Result result = reader.decode(bitmap);
String text = result.getText();
success = true;
Log.d(TAG, "onImageAvailable: text = " + text);
} catch (NotFoundException e) {
Log.e(TAG, "onImageAvailable: ", e);
}
}
image.close();
if (success) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ScanActivity.this, "扫描成功", Toast.LENGTH_SHORT).show();
}
});
}
}
};
private static class CompareSizesByArea implements Comparator<Size> {
@Override
public int compare(Size lhs, Size rhs) {
return Long.signum((long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight());
}
}
private void toggleFlash() {
if (mCameraDevice == null || !mFlashSupported) {
return;
}
try {
mFlashEnabled = !mFlashEnabled;
mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, mFlashEnabled ? CaptureRequest.FLASH_MODE_TORCH : CaptureRequest.FLASH_MODE_OFF);
mCameraDevice.createCaptureSession(Arrays.asList(mSurfaceView.getHolder().getSurface(), mImageReader.getSurface()), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
try {
cameraCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
Log.e(TAG, "onConfigured: ", e);
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Log.e(TAG, "onConfigureFailed: ");
}
}, null);
} catch (CameraAccessException e) {
Log.e(TAG, "toggleFlash: ", e);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
toggleFlash();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
```
在该示例中,我们使用 ImageReader 获取相机预览数据,并使用 ZXing 库进行识别。同时,我们还实现了打开闪光灯的功能,可以使用音量键触发。需要注意的是,在使用打开闪光灯的功能时,需要先检查相机设备是否支持闪光灯。
阅读全文