如何从本地选择图片文件
使用Intent调用系统相册后,onActivityResult
函数返回的是Uri
格式的路径
/**
* 打开系统相册
*/
private void openSysAlbum() {
Intent innerIntent = new Intent();
if (Build.VERSION.SDK_INT < 19) {
innerIntent.setAction(Intent.ACTION_GET_CONTENT);
} else {
innerIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
innerIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
startActivityForResult(wrapperIntent, SELECT_IMAGE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SELECT_IMAGE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
scanningImage(uri);
}
break;
}
}
如何将Uri的路径转化为Bitmap
获取Bitmap现在我查到两种解决方案:
- 一种是根据Uri查询图库的数据库,找到文件的真实路径,然后再解析为Bitmap;
- 第二种(http://blog.sina.com.cn/s/blog_5de73d0b0100zfm8.html)是直接根据Uri直接获取到InputStream,再解析为Bitmap。
两种方案都可以,我感觉第二种方案更加靠谱一点,因为系统的数据库可能会更改,但是直接获取InputStream是不会变的。
第一种方案代码
/**
*
* @param intent
*/
public void ecognition(Intent intent) {
String photo_path = null;
// 获取选中图片的路径
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(intent.getData(), proj, null, null, null);
if (cursor.moveToFirst()) {
photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (photo_path == null) {
photo_path = Utils.getPath(getApplicationContext(), intent.getData());
}
}
cursor.close();
QRDecode.decodeQR(photo_path, this);
}
/**
* 解析二维码图片
*
* @param picturePath
* @param listener
* @return
*/
public static void decodeQR(String picturePath, OnScannerCompletionListener listener) {
try {
decodeQR(loadBitmap(picturePa