Android studio调用本机相机
时间: 2024-05-13 14:14:14 浏览: 66
在Android Studio中调用本机相机可以通过以下步骤实现:
1.在AndroidManifest.xml文件中添加相机权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
```
2.在布局文件中添加一个SurfaceView,用于显示相机预览:
```xml
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3.在Activity中获取相机实例,并设置SurfaceView作为相机预览的显示:
```java
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// do nothing
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
});
}
```
4.在Activity中添加一个按钮,用于拍照:
```java
public void onTakePhotoButtonClick(View view) {
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// 处理拍照结果
}
});
}
```
注意:拍照结果是一个字节数组,需要根据需要进行转换和处理,比如保存到本地文件或上传到服务器。
阅读全文