官方文檔
https://developer.android.com/training/camera/photobasics?hl=zh-cn#java
拍照后的圖片如果希望保存再公共存儲空間,需要申請權(quán)限
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
//獲取公共存儲空間的方法
File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
如果是存儲在私用空間,對于4.4以下的系統(tǒng)還是要申請權(quán)限,對于4.4及以上的系統(tǒng)則不需要,因為其他app訪問不了。
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
...
</manifest>
//獲取私有存儲空間的方法
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
創(chuàng)建文件用于存儲拍攝的圖片。
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;
}
發(fā)起調(diào)用相機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);
}
}
}
創(chuàng)建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>
創(chuàng)建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中處理拍照結(jié)果
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);
}
遇到的問題:
拍照后調(diào)用裁剪崩潰:FileUriExposedException
因為Android 7.0不允許intent帶有file://的URI離開自身的應用了,要不然會拋出FileUriExposedException
想要在自己應用和其他應用之間共享File數(shù)據(jù),只能使用content://的方式
改成如下:
if (currentPhotoPath != null) {
File file = new File(currentPhotoPath);
Uri contentUri = FileProvider.getUriForFile(this, "ecp.PhotoPicker", file);
cropPic(contentUri);
}
小米的手機無法調(diào)用裁剪功能:
沒有打開裁剪界面、沒有日志報錯。。。
cropIntent.putExtra("return-data", false);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
調(diào)用裁剪Intent時,設(shè)為不返回bitmap,而是保存到文件中。
這是可以成功打開裁剪界面了。但是裁剪完,點擊確定,又出現(xiàn)一下問題
照片裁剪后點擊確定出現(xiàn): “保存時出現(xiàn)錯誤,保存失敗”
在5.1的設(shè)備測試沒問題,應該時8.1的存儲策略改變了。
保存的uri改成:
Uri uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
調(diào)用相機拍照后打開裁剪功能: “圖片加載失敗”
加上這一句就可以了。
cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);