调用手机前置摄像头拍照的代码
时间: 2023-09-08 14:14:56 浏览: 244
以下是使用 Android 相机 API 调用前置摄像头拍照的代码示例:
```java
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_CAMERA_PERMISSION = 2;
private SurfaceView mSurfaceView;
private Camera mCamera;
private boolean mIsPreviewing = false;
private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// 在这里处理拍照后的数据
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = findViewById(R.id.surfaceView);
mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
openCamera();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// 在这里设置预览尺寸等参数
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
});
Button captureButton = findViewById(R.id.captureButton);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mIsPreviewing) {
mCamera.takePicture(null, null, mPictureCallback);
}
}
});
}
private void openCamera() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
return;
}
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
try {
mCamera.setPreviewDisplay(mSurfaceView.getHolder());
mCamera.startPreview();
mIsPreviewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
mIsPreviewing = false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
// 权限被拒绝,可以在这里做一些提示
}
}
}
```
需要注意的是,上述代码只是一个示例,可能需要根据具体情况进行适当的修改。例如,需要在 AndroidManifest.xml 文件中添加相应的权限声明:
```xml
<uses-permission android:name="android.permission.CAMERA" />
```
此外,还需要在 layout 文件中添加一个 SurfaceView 控件,用于显示相机预览图像:
```xml
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
最后,记得在 AndroidManifest.xml 文件中声明该 Activity:
```xml
<activity android:name=".MainActivity" />
```
阅读全文