1.在res/xml目录中新建一个file_paths.xml
<?xml version="1.0" encoding="utf-8"?><paths><files-path name="files" path="files" /><cache-path name="name" path="path" /><external-path name="external" path="." /><external-files-path name="name" path="path" /><external-cache-path name="name" path="path" /></paths>
2.在清单文件中申明FileProvider
<!-- 7.0文件权限 --><provider android:name="android.support.v4.content.FileProvider"android:authorities="${applicationId}.fileprovider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" /></provider>
3.从相册获取图片
val intent = Intent()intent.action = Intent.ACTION_PICKintent.type = "image/*"startActivityForResult(intent, REQUEST_IMAGE)
4.从相机城乡获取图片
private fun openCamera() {// 创建File对象,用于存储拍照后的图片val outputImage = File(externalCacheDir, "output_image.jpg")try {if (outputImage.exists()) {outputImage.delete()}outputImage.createNewFile()} catch (e: IOException) {e.printStackTrace()}cameraImageUri = if (Build.VERSION.SDK_INT < 24) {Uri.fromFile(outputImage)} else {FileProvider.getUriForFile(this,packageName + ".fileprovider",outputImage)}// 启动相机程序val intent = Intent("android.media.action.IMAGE_CAPTURE")intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri)startActivityForResult(intent, TAKE_PHOTO)}
5.获取图片结果
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {super.onActivityResult(requestCode, resultCode, data)when (requestCode) {REQUEST_IMAGE -> run {if (data != null) {val uri = data.datacropPhoto(uri)}}PICTURE_CUT -> try {iv_head_activity_setting.setImageBitmap(BitmapFactory.decodeFile(ImageUtil.getImageAbsolutePath(this, outputUri)))} catch (e: Exception) {println("获取异常")}TAKE_PHOTO ->cropPhoto(cameraImageUri)}}
6.裁剪图片
/*** 裁剪图片*/private fun cropPhoto(uri: Uri?) {if (uri == null) return// 创建File对象,用于存储裁剪后的图片,避免更改原图val file = File(externalCacheDir, "crop_head.jpg")try {if (file.exists()) {file.delete()}file.createNewFile()} catch (e: IOException) {e.printStackTrace()}outputUri = Uri.fromFile(file)val intent = Intent("com.android.camera.action.CROP")if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)}intent.setDataAndType(uri, "image/*")intent.putExtra("aspectX", 1)intent.putExtra("aspectY", 1)intent.putExtra("crop", "true")//可裁剪intent.putExtra("scale", true)//支持缩放intent.putExtra("return-data", false)intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri)intent.putExtra("outputFormat", pressFormat.JPEG.toString())//输出图片格式intent.putExtra("noFaceDetection", true)//取消人脸识别startActivityForResult(intent, PICTURE_CUT)}
7.通过Uri获取图片的真实地址
/*** 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换** @param context* @param imageUri*/@TargetApi(19)public static String getImageAbsolutePath(Context context, Uri imageUri) {if (context == null || imageUri == null)return null;if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {if (isExternalStorageDocument(imageUri)) {String docId = DocumentsContract.getDocumentId(imageUri);String[] split = docId.split(":");String type = split[0];if ("primary".equalsIgnoreCase(type)) {return Environment.getExternalStorageDirectory() + "/" + split[1];}} else if (isDownloadsDocument(imageUri)) {String id = DocumentsContract.getDocumentId(imageUri);Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));return getDataColumn(context, contentUri, null, null);} else if (isMediaDocument(imageUri)) {String docId = DocumentsContract.getDocumentId(imageUri);String[] split = docId.split(":");String type = split[0];Uri contentUri = null;if ("image".equals(type)) {contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else if ("video".equals(type)) {contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;} else if ("audio".equals(type)) {contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;}String selection = MediaStore.Images.Media._ID + "=?";String[] selectionArgs = new String[]{split[1]};return getDataColumn(context, contentUri, selection, selectionArgs);}} // MediaStore (and general)else if ("content".equalsIgnoreCase(imageUri.getScheme())) {// Return the remote addressif (isGooglePhotosUri(imageUri))return imageUri.getLastPathSegment();return getDataColumn(context, imageUri, null, null);}// Fileelse if ("file".equalsIgnoreCase(imageUri.getScheme())) {return imageUri.getPath();}return null;}public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {Cursor cursor = null;String column = MediaStore.Images.Media.DATA;String[] projection = {column};try {cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {int index = cursor.getColumnIndexOrThrow(column);return cursor.getString(index);}} finally {if (cursor != null)cursor.close();}return null;}/*** @param uri The Uri to check.* @return Whether the Uri authority is ExternalStorageProvider.*/public static boolean isExternalStorageDocument(Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is DownloadsProvider.*/public static boolean isDownloadsDocument(Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is MediaProvider.*/public static boolean isMediaDocument(Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is Google Photos.*/public static boolean isGooglePhotosUri(Uri uri) {return "com.google.android.apps.photos.content".equals(uri.getAuthority());}