清單文件中增加對應權限,動態申請權限(此部分請參考Android 動態申請權限,在此不作為重點描述)
private static final int REQUEST_CODE_ALBUM = 100;//打開相冊
private static final int REQUEST_CODE_CAMERA = 101;//打開相機
//調用相冊
private void openAlbum(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_ALBUM);
}
//調用相機
private void openCamera1(){
Intent intent;
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_ALBUM && resultCode == RESULT_OK){
if (data != null) {
// 照片的原始資源地址
Uri uri = data.getData();
String path = uri.getPath();
ContentResolver cr = context.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
/* 將Bitmap設定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(), e);
}
}
}else if(requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK){
if(data != null && data.getData() != null){
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bitmap = extras.getParcelable("data");
/* 將Bitmap設定到ImageView */
imageView.setImageBitmap(bitmap);
//可將圖片保存下來,用於上傳或其他操作(如果不需要可以省略此步)
String path = savePicToSdcard(image,Environment.getExternalStorageDirectory().getPath(),System.currentTimeMillis() + ".jpg");
}
}
}
}
public static String savePicToSdcard(Bitmap bitmap, String path, String fileName) {
String filePath = "";
if (bitmap != null) {
filePath = path + File.separator + fileName;
File destFile = new File(filePath);
OutputStream os = null;
try {
os = new FileOutputStream(destFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (IOException e) {
filePath = "";
}
}
return filePath;
}
上述相機方法相片清晰度低,獲取的是返回對象中的略縮圖;如對照片清晰度有要求,可以在上面方法的基礎上進行修改,方法如下:
需要在清單文件中application中增加如下代碼:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
創建file_paths.xml文件
項目目錄res下創建xml文件夾,xml文件夾下創建file_paths.xml文件,文件內容:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_storage_root"
path="." />
</paths>
配置完成后,修改增加如下代碼:
private static final int REQUEST_RESULT_CODE = 102;//裁剪后保存
//調用相機(指定相機拍攝照片保存地址,相片清晰度高)
private void openCamera2(){
String photoPath = Environment.getExternalStorageDirectory().getPath()+"/"+File.separator+"123.jpg";
File pictureFile = new File(photoPath);
Uri picUri;
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String packageName = context.getApplicationContext().getPackageName();
picUri = FileProvider.getUriForFile(context, new StringBuilder(packageName).append(".fileprovider").toString(), pictureFile);
} else {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
picUri = Uri.fromFile(pictureFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_ALBUM && resultCode == RESULT_OK){
if (data != null) {
// 照片的原始資源地址
Uri uri = data.getData();
String path = uri.getPath();
ContentResolver cr = context.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
/* 將Bitmap設定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(), e);
}
}
}else if(requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK){
File tempFile = new File(photoPath);
cropImg(getImageContentUri(tempFile));//對照片進行裁剪保存
}else if(requestCode ==REQUEST_RESULT_CODE && resultCode == RESULT_OK){
try {
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(mUriPath));
/* 將Bitmap設定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public Uri getImageContentUri(File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
public void cropImg(Uri uri){
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
//實現對圖片的裁剪,必須要設置圖片的屬性和大小
intent.putExtra("crop", "true"); //滑動選中圖片區域
intent.putExtra("aspectX", 1); //裁剪框比例1:1
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 700); //輸出圖片大小
intent.putExtra("outputY", 700);
intent.putExtra("return-data", true); //有返回值
String mLinshi = System.currentTimeMillis() + ".jpg";
photoFile = new File(Environment.getExternalStorageDirectory().getPath(), mLinshi);
mUriPath = Uri.parse("file://" + photoFile.getAbsolutePath());
//將裁剪好的圖輸出到所建文件中
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPath);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//注意:此處應設置return-data為false,如果設置為true,是直接返回bitmap格式的數據,耗費內存。設置為false,然后,設置裁剪完之后保存的路徑,即:intent.putExtra(MediaStore.EXTRA_OUTPUT, uriPath);
intent.putExtra("return-data", false);
startActivityForResult(intent, REQUEST_RESULT_CODE);
}
