改方法直接可以获取当前系统相册照片。不需要打开相册直接读取。
public void getRealPathFromURI(ImageView imageView){
//设置要返回的字段
try {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
DebugLogs.e("TestFile------>SD card is not avaiable/writeable right now.");
return;
}
String[] columns = { MediaStore.Images.Media.DATA};
//执行查询,返回一个cursor
ContentResolver cr = getSdkActivity().getContentResolver();
cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, null);
fileColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if (cursor.moveToLast()) {
imageFilePath = cursor.getString(fileColumn);
if(Build.VERSION.SDK_INT < 14) {
cursor.close();
}
}
DebugLogs.e("---获取相册-->"+imageFilePath);
BitmapFactory.Options bmFactoryOptions = new BitmapFactory.Options();
bmFactoryOptions.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath, bmFactoryOptions);
//创建操作图片是用的matrix对象
Matrix matrix=new Matrix();
//旋转图片动作
int degree = readPictureDegree(imageFilePath);
matrix.postRotate(degree);
//创建新图片
Bitmap resizedBitmap=Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
imageView.setImageBitmap(resizedBitmap);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}catch (Exception e){
e.printStackTrace();
}
}
为了保证读取相册都是正方向,所以要加上选择照片的方法。
/**
* 读取照片exif信息中的旋转角度
* @param path 照片路径
* @return角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
好了以上方法就可以直接读取系统相册,切不需要打开相册目录。