1.选取照片并显示
启动相册的动作为
public static final java.lang.String ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT";
隐式启动相册的代码为:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent,ACTION_CHOOSE);
注意这里没有把return-data设置为false,因为我们就是要利用data里面的值来显示图片。
最后在onActivityResult中接收
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case ACTION_CHOOSE:
try {
if(data!=null){
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(data.getData()));
Bitmap smallBmp = setScaleBitmap(photo, 2);
imageview.setImageBitmap(smallBmp );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
}
}
}
为了防止图片显示不下,先把它压缩为一半,代码如下:
private Bitmap setScaleBitmap(Bitmap photo,int SCALE) {
if (photo != null) {
//为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
//这里缩小了1/2,但图片过大时仍然会出现加载不了,但系统中一个BITMAP最大是在10M左右,我们可以根据BITMAP的大小
//根据当前的比例缩小,即如果当前是15M,那如果定缩小后是6M,那么SCALE= 15/6
Bitmap smallBitmap = zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE);
//释放原始图片占用的内存,防止out of memory异常发生
photo.recycle();
return smallBitmap;
}
return null;
}
public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}
但是由于data所能传递的最大值为1M,所以当我们的图片太大时,选取的图片并不会显示到ImageView中。
2.选取照片裁剪显示
启动相册,并且配置参数,将return-data设置为false,我们用uri来接收结果。
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 1000);
intent.putExtra("outputY", 1000);
intent.putExtra("scale", true);
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent,ACTION_CHOOSE);
直接从uri中获取图片,显示在ImageView里面:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case ACTION_CHOOSE:
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
Bitmap smallBmp = setScaleBitmap(photo, 2);
imageview.setImageBitmap(smallBmp );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
}
}
看着好像没什么事情,但问题来了:在有些手机上根本出不来裁剪页面,这是为什么呢?那这里要怎么办呢?有没有一种方法能找到用户点击的图片的地址呢?如果能找到地址,那在用户点击一个图片后,再调用裁剪的Intent,从本地读取图片数据传进去裁剪Intent让它来裁剪,这样就绕过了直接通过Intent数据传递的大小限制。
3.从相册选取并裁剪(通过路径)
整体过程是这样的
先调用选择图片Intent:
public void choosePhoto(View view){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent,ACTION_CHOOSE);
}
然后在接收时,找到图片路径,生成对应的URI,转给裁剪页面:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case ACTION_CHOOSE:
String path = Util.getImageAbsolutePath(this,data.getData());
File file = new File(path);
Uri uri = Uri.fromFile(file);
cropImage(uri);
break;
}
然后是裁剪:
public void cropImage(Uri uri){
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri,"image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 700);
intent.putExtra("outputY", 700);
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent,ACTION_CROP);
裁剪后,将图片保存在本地的uri中,在onActivityResult中接收,将Uri中的图片取出来。
case ACTION_CROP:
try { Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(cropUri)); Bitmap smallBmp = setScaleBitmap(photo, 2); imageview.setImageBitmap(smallBmp ); } catch (FileNotFoundException e) { e.printStackTrace(); }
4、从相册选择图像并显示的终极方案
过程是这样的:
启动图库:
public void choosePhoto(View view){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent,ACTION_CHOOSE);
}
在onActivityResult中接收返回来的数据,根据data获取图片的路径,然后根据路径生成uri,直接从uri中获得bitmap,显示给ImageView.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case ACTION_CHOOSE:
if(data!=null){
String path = Util.getImageAbsolutePath(this,data.getData());
File file = new File(path);
Uri uri = Uri.fromFile(file);
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
Bitmap smallBmp = setScaleBitmap(photo, 2);
imageview.setImageBitmap(smallBmp );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
}
}
}
}
最后给出根据Uri获取图片地址的代码:
public static String getImageAbsolutePath(Activity 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 address
if (isGooglePhotosUri(imageUri))
return imageUri.getLastPathSegment();
return getDataColumn(context, imageUri, null, null);
}
// File
else 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());
}
}