经常用到手机相册功能的童鞋都知道,小米手机获取相册图片跟其他手机都不一样,这里有一个工具类
也是在网上找的,亲测有效,可以使用。记得,获取相册之前得先动态获取权限,前面一篇说了如何
动态获取权限,不知道的童鞋可以去瞅瞅。获取手机相片的工具类如下,拷过去用即可
public class MiPictureHelper {
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
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];
}
}
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);
}
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);
}
}
else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
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;
}
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());
}
private static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
我还加了几个常用到的方法,如下,注释写的很清楚:
/**
* Save Bitmap to a file.保存图片到SD卡。
*
* @param bitmap
* @param _file
* @return error message if the saving is failed. null if the saving is
* successful.
* @throws IOException
*/
public static void saveBitmapToFile(Bitmap bitmap, String _file) throws IOException {
BufferedOutputStream os = null;
try {
File file = new File(_file);
int end = _file.lastIndexOf(File.separator);
String _filePath = _file.substring(0, end);
File filePath = new File(_filePath);
if (!filePath.exists()) {
filePath.mkdirs();
}
file.createNewFile();
os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
Log.v("WZ", e.getMessage(), e);
}
}
}
}
/**
* 图片转换成byte[]数组
*
* @param bitmap 要转换图片的bitmap对象
* @return byte[]数组
*/
public static byte[] getBitmapByte(Bitmap bitmap) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return out.toByteArray();
}
/**
* 图片质量压缩
*
* @param image 要压缩图片的bitmap对象
* @return
*/
public static Bitmap compressImage(Bitmap image) {
if (image == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 10;
if (options <= 0) {
break;
}
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
/**
* 图片按比例大小压缩
*
* @param srcPath 图片路径
* @return
*/
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;
float ww = 480f;
int be = 1;
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
if (bitmap == null) {
return null;
} else {
return compressImage(bitmap);
}
}
调用方式如下:
if (CONSTANT.RequestCode.ALBUMRESOULT == requestCode) {
if (data != null) {
try {
Uri uri = data.getData();
picturePath = MiPictureHelper.getPath(context, uri);
Bitmap saveMyBitmap = MiPictureHelper.compressImage(MiPictureHelper.getimage(picturePath));
if (saveMyBitmap == null) {
return;
}
img.setVisibility(View.VISIBLE);
img.setImageBitmap(saveMyBitmap);
imgAdd.setVisibility(View.GONE);
saveMyBitmap = null;
} catch (Exception e) {
}
}
}
工具类下载