官方文档
https://developer.android.com/training/camera/photobasics?hl=zh-cn#java
拍照后的图片如果希望保存再公共存储空间,需要申请权限
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
//获取公共存储空间的方法
File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
如果是存储在私用空间,对于4.4以下的系统还是要申请权限,对于4.4及以上的系统则不需要,因为其他app访问不了。
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
...
</manifest>
//获取私有存储空间的方法
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
创建文件用于存储拍摄的图片。
String currentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
发起调用相机Intent
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
创建provider组件
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
...
</application>
创建res/xml/file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
在onActivityResult中处理拍照结果
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case SELECT_PIC_BY_TACK_PHOTO:
if (currentPhotoPath != null) {
Glide.with(this)
.load(currentPhotoPath)
.into(imageView);
}
}
}
添加到媒体库
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Decode a scaled image
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(currentPhotoPath, boptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, boptions);
imageView.setImageBitmap(bitmap);
}
遇到的问题:
拍照后调用裁剪崩溃:FileUriExposedException
因为Android 7.0不允许intent带有file://的URI离开自身的应用了,要不然会抛出FileUriExposedException
想要在自己应用和其他应用之间共享File数据,只能使用content://的方式
改成如下:
if (currentPhotoPath != null) {
File file = new File(currentPhotoPath);
Uri contentUri = FileProvider.getUriForFile(this, "ecp.PhotoPicker", file);
cropPic(contentUri);
}
小米的手机无法调用裁剪功能:
没有打开裁剪界面、没有日志报错。。。
cropIntent.putExtra("return-data", false);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
调用裁剪Intent时,设为不返回bitmap,而是保存到文件中。
这是可以成功打开裁剪界面了。但是裁剪完,点击确定,又出现一下问题
照片裁剪后点击确定出现: “保存时出现错误,保存失败”
在5.1的设备测试没问题,应该时8.1的存储策略改变了。
保存的uri改成:
Uri uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
调用相机拍照后打开裁剪功能: “图片加载失败”
加上这一句就可以了。
cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);