java调用手机摄像头
时间: 2023-09-05 09:09:02 浏览: 159
要在Java中调用手机摄像头,需要使用Android SDK提供的相机API。以下是一个简单的示例代码,可以启动相机并显示预览:
```java
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class CameraActivity extends Activity implements SurfaceHolder.Callback {
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button captureButton = (Button) findViewById(R.id.captureButton);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (camera != null) {
camera.takePicture(null, null, pictureCallback);
}
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (camera != null) {
camera.stopPreview();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// 处理拍摄的照片数据
}
};
}
```
要调用此Activity,需要在应用程序的AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
```
并在应用程序的build.gradle文件中添加以下依赖项:
```groovy
dependencies {
implementation 'com.android.support:support-v4:28.0.0'
}
```
阅读全文