呵呵,今天很高兴,因为自己正式步入准爸爸阶段了!特此记录下!
好吧,今天,我接着上次的问题讲解,如何从android4.4以上系统进行选图而避免报错,而
android4.4.4 获取系统相册图片出错的问题(一)
中介绍的那种方式,其实在性能方面的话,还是一般,因为每次读取一张图片,它都要在本地生成一张,造成存储空间的浪费。今天介绍的这种方法,是根据网上的不同的资料进行的整理。
第一步:也就是我们调转到我们的系统相册进行图片的选择
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);// ACTION_OPEN_DOCUMENT
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {/**4.4系统以上**/
startActivityForResult(intent, SELECT_PIC_KITKAT);
} else {
startActivityForResult(intent, SELECT_PIC);
}
第二步自然就是在onActivityResult中进行处理
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_PIC_KITKAT:
if (resultCode != Activity.RESULT_OK) {
return;
}
String path = "";
if (DocumentsContract.isDocumentUri(MainActivity.this,
data.getData())) {
// path = selectImage(MainActivity.this, data);
path = getPath(data);
} else {
path = getPath(MainActivity.this, data);
}
Message msg = new Message();
msg.obj = path;
handler.sendMessage(msg);
break;
case SELECT_PIC:
if (resultCode != Activity.RESULT_OK) {
return;
}
Message msg1 = new Message();
msg1.obj = getPath(data);
handler.sendMessage(msg1);
break;
}
}
好,关键代码来了,如下:
public static String getPath(final Context context, Intent data) {
Uri uri = data.getData();
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];
}
// TODO handle non-primary volumes
}
// 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());
}
现在就是通过handler进行本地的显示:
private Handler handler = new Handler(Looper.getMainLooper()) {
public void handleMessage(android.os.Message msg) {
String path = (String) msg.obj;
// Bitmap myBitmap = getLoacalBitmap(path);
Bitmap bitmap = LocalImageCompression.comp(path);
img.setImageBitmap(bitmap);
};
};
其中用到了一个通过本地路径进行图片的处理,主要是相册图片的size太大了,显示不了,
/** * @方法说明:图片按比例大小压缩方法(根据路径获取图片并压缩) * @方法名称:getimage * @param srcPath * @return * @返回值:Bitmap */
public static Bitmap comp(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
/** 开始读入图片,此时把options.inJustDecodeBounds 设回true了**/
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);/** 此时返回bm为空**/
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
/** 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为**/
float hh = 800f;/** 这里设置高度为800f**/
float ww = 480f;/** 这里设置宽度为480f**/
/** 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可**/
int be = 1;/** 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;/** 设置缩放比例**/
/** 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了**/
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);/** 压缩好比例大小后再进行质量压缩**/
}
源码地址:http://yunpan.cn/cJ8WZm9NsnvuX (提取码:3719)