在系统相机中拍照,获取照片文件的路径。代码实现,通用简介
时间: 2023-12-19 16:04:49 浏览: 84
获取照片文件的路径可以通过以下步骤实现:
1. 获取相机对象
```java
Camera camera = Camera.open();
```
2. 创建相机回调函数
```java
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// 处理照片数据
}
};
```
3. 开始预览相机
```java
SurfaceView surfaceView = findViewById(R.id.surfaceView);
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
```
4. 拍照并获取照片文件路径
```java
camera.takePicture(null, null, mPicture);
```
在 `onPictureTaken` 回调函数中,可以将照片数据写入文件,并获取照片文件的路径。例如:
```java
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Log.d(TAG, "Picture saved: " + pictureFile.getAbsolutePath());
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
```
`getOutputMediaFile` 方法用于创建照片文件并返回文件对象。例如:
```java
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
return mediaFile;
}
```
注意需要添加相应的权限,例如相机权限和读写存储权限。
阅读全文