在项目开发中,免不了要与图片打交道,但是获取图片的大部分方式都是通过拍照和选择相册中的照片获取的。下面就来说一下如何调用系统拍照于相册功能获取图片,
首先要知道的是,不管是相机还是相册,其实本质上都是一个app,所以基本原理就是:调用app(相机或相册)——获取回调(也就的图片的URI)——根据URI取得图片的Bitmap——将Bitmap填充到Imageview里面,基本就是这样,接下来上代码:
第一步:调用相机或相册APP
调用系统相机:
private static final String IMAGE_FILE_LOCATION = "file:///sdcard/user_face.jpg";
private Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, SELECT_CAMER);
其中imageUri是你保存拍照存储的位置
调用系统相册:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PICTURE);
第二步:获取回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_PICTURE:
if (resultCode == RESULT_OK) {
// 读取相册缩放图片
Uri tag = data.getData();
int sdkV = android.os.Build.VERSION.SDK_INT;
if (sdkV >= 19) {
String path = getPath(this, tag);
tag = Uri.parse("file://" + path);
}
startPhotoZoom(tag);
}
break;
case SELECT_CAMER:
if (resultCode == RESULT_OK) {
startPhotoZoom(imageUri);
}
break;
case RESULT_REQUEST_CODE:
if (data == null) {
return;
}
Bundle extras = data.getExtras();
if (extras != null) {
bmp = extras.getParcelable("data");
person_face_img.setImageBitmap(bmp);
setFaceData(bmp);
}
break;
default:
break;
}
}
根据requestCode判断是相机回调还是相册回调,如果的相册的话,由于4.4版以后选择照片返回的不再是之前的URI,所以我们要对其做下特殊处理,看代码:
Uri tag = data.getData();
int sdkV = android.os.Build.VERSION.SDK_INT;
if (sdkV >= 19) {
String path = getPath(this, tag);
tag = Uri.parse("file://" + path);
}
// 以下是关键,原本uri返回的是file:///...来着的,android4.4返回的是content:///...
@SuppressLint("NewApi")
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 null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
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 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());
}
这一步完成后,基本算是成功的大半,接下来就是图片处理的事了,有些手机像素高拍出来的照片较大,如果直接使用的话容易造成内存溢出,所以我们可以选择对图片进行裁剪,大家可以看到startPhotoZoom(imageUri);这个方法
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("return-data", true);
startActivityForResult(intent, RESULT_REQUEST_CODE);
}
调用系统的裁剪后取得裁剪后的回调:
if (data == null) {
return;
}
Bundle extras = data.getExtras();
if (extras != null) {
bmp = extras.getParcelable("data");
person_face_img.setImageBitmap(bmp);
setFaceData(bmp);
}
其中的bmp就的裁剪后的bitmap,获取bitmap后就可以往imageview里面填充了