Android studio 拍照功能详细教程
时间: 2023-06-09 19:06:03 浏览: 128
好的,关于Android Studio的拍照功能,以下是详细的教程:
1. 打开Android Studio并创建一个新项目
2. 在项目中打开并编辑 activity_main.xml 文件
3. 添加一个ImageView组件和一个Button组件到布局文件中,如下所示:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
<Button
android:id="@+id/buttonCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Capture" />
</RelativeLayout>
```
4. 在MainActivity.java文件中实现拍照功能。首先,声明一个全局的变量mImageUri来保存拍摄照片的Uri
```
private Uri mImageUri;
```
5. 添加以下代码用于按钮点击事件处理:
```
Button b_photo = findViewById(R.id.buttonCapture);
ImageView iv_photo = findViewById(R.id.imageView);
b_photo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); // set the image file name
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); // start the image capture intent
}
});
```
6. 添加以下代码将拍摄的照片显示在ImageView组件上:
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check if the result is ok
if (resultCode == RESULT_OK) {
// Image captured and saved to mImageUri
iv_photo.setImageURI(mImageUri);
} else {
// User cancelled the image capture
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
```
7. 最后添加以下代码来创建一个保存照片的文件:
```
private static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final String IMAGE_DIRECTORY_NAME = "MyApp";
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
```
好了,以上就是详细的Android Studio拍照功能教程,希望对你有所帮助。
阅读全文