Android-->拍照/相册选择照片(从Uri中获取图片路径)

对于一个APP来说, 照片选择是经常会用到的功能.

拍照获取照片
此方法需要指定照片的路径, 这是最简单的获取照片的方式了;

/**
 * 拍照获取图片, imageUri.getPath() 图片路径
 */
public static void getPhotoFromCamera(Activity context, int requestCode, Uri imageUri) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name
    context.startActivityForResult(intent, requestCode);
}
//创建照片的路径
public static String createPhotoPath(Context context) {
     String path = FileUtil.getPath("angcyo/Photo");
     return path + "/" + UUID.randomUUID();
 }

//获取SD卡下的一个安全路径
public static String getPath(String name) {
   File file = new File(getSDPath() + "/" + name);
   if (!file.exists()) {
       try {
           file.mkdirs();
       } catch (Exception e) {
           e.printStackTrace();
           return "";
       }
   }
   return file.getAbsolutePath();
}

//获取SD卡的路径
public static String getSDPath() {
   return isExternalStorageWritable() ? Environment
           .getExternalStorageDirectory().getPath() : Environment
           .getDownloadCacheDirectory().getPath();
}

相册选择
这就坑了, 因为不同的手机, 不同的版本返回的数据不一样. 所以需要区分处理;
有些 返回数据的shceme是content, 这种需要查询数据库才能拿到路径.
有些 返回数据的shceme是file, 这种就可以直接getPath()拿到路径,相对简单.

/**
 * 相册选择照片, 需要特殊处理才能获取到图片路径
 */
public static void getPhotoFromPhotos(Activity context, int requestCode) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    context.startActivityForResult(Intent.createChooser(intent, "选择图片"), requestCode);
}
//通用的从uri中获取路径的方法, 兼容以上说到的2个shceme
public static String getPath(final Context context, final Uri uri) {

   final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
   // DocumentProvider
   if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
       // ExternalStorageProvider
       if (isExternalStorageDocument(uri)) {
           final String docId = DocumentsContract.getDocumentId(uri);
           final String[] split = docId.split(":");
           final String type = split[0];

           if ("primary".equalsIgnoreCase(type)) {
               return Environment.getExternalStorageDirectory() + "/" + split[1];
           }

       }
       // DownloadsProvider
       else if (isDownloadsDocument(uri)) {

           final String id = DocumentsContract.getDocumentId(uri);
           final Uri contentUri = ContentUris.withAppendedId(
                   Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

           return getDataColumn(context, contentUri, null, null);
       }
       // MediaProvider
       else if (isMediaDocument(uri)) {
           final String docId = DocumentsContract.getDocumentId(uri);
           final String[] split = docId.split(":");
           final 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;
           }

           final String selection = "_id=?";
           final String[] selectionArgs = new String[]{
                   split[1]
           };

           return getDataColumn(context, contentUri, selection, selectionArgs);
       }
   }
   // MediaStore (and general)
   else if ("content".equalsIgnoreCase(uri.getScheme())) {

       // Return the remote address
       if (isGooglePhotosUri(uri))
           return uri.getLastPathSegment();

       return getDataColumn(context, uri, null, null);
   }
   // File
   else if ("file".equalsIgnoreCase(uri.getScheme())) {
       return uri.getPath();
   }

   return "";
}

public static long getId(Context context, Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final 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;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getIdColumn(context, contentUri, selection, selectionArgs);
        }
    } else {
        return getIdColumn(context, uri, null, null);
    }
    return 0;
}

public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return "";
}
public static long getIdColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_id";
    final String[] projection = {column};

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getLong(index);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return 0;
}
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

接收数据

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == CODE_PHOTO) {
        } else if (requestCode == CODE_CAMERA) {
        } else if (requestCode == CODE_CROP) {
        }
    }
}

剪切图片

/**
 * 用给定的uri,调用 裁剪程序
 */
public static void cropImageByUri(Activity context, int requestCode, Uri from, Uri to, int outputX, int outputY) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(from, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("scale", true);
    intent.putExtra("scaleUpIfNeeded", true);
    intent.putExtra("aspectX", 1);//剪切框宽高比例
    intent.putExtra("aspectY", 2);//剪切框宽高比例
    intent.putExtra("outputX", outputX);
    intent.putExtra("outputY", outputY);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, to);
    intent.putExtra("return-data", false);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true); // no face detection
    context.startActivityForResult(intent, requestCode);
}

Android-->拍照/相册选择照片(从Uri中获取图片路径)_第1张图片


至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.

你可能感兴趣的:(Android)