Android Studio拍照裁剪
时间: 2023-11-03 15:01:15 浏览: 145
Android Studio拍照裁剪的方法如下:
1. 首先,在`AndroidManifest.xml`文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 在你的Activity中,添加以下代码来打开相机拍照:
```java
private static final int REQUEST_IMAGE_CAPTURE = 1;
private Uri imageUri;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// 创建一个临时文件来保存拍摄的照片
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// 错误处理
}
if (photoFile ! null) {
// 获取文件的URI
imageUri = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
// 将URI添加到Intent中
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
// 启动相机
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private File createImageFile() throws IOException {
// 创建一个唯一的文件名
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* 前缀 */
".jpg", /* 后缀 */
storageDir /* 目录 */
);
return image;}
```
3. 在`onActivityResult`方法中,处理拍摄完成后的图片裁剪:
```java
private static final int REQUEST_IMAGE_CROP = 2;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// 启动裁剪
performCrop();
} else if (requestCode == REQUEST_IMAGE_CROP && resultCode == RESULT_OK) {
// 获取裁剪后的图片
Bundle extras = data.getExtras();
Bitmap croppedBitmap = (Bitmap) extras.get("data");
// 在ImageView中显示裁剪后的图片
imageView.setImageBitmap(croppedBitmap);
}
}
private void performCrop() {
try {
// 创建临时文件,用于保存裁剪后的图片
File cropFile = createImageFile();
Uri cropUri = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
cropFile);
// 启动裁剪Intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cropIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, REQUEST_IMAGE_CROP);
} catch (IOException ex) {
// 错误处理
}
}
```
阅读全文