接之前的博客:
调用之前的方法对于大部分手机是没有问题的,但是今天拿了红米note测试之后,结果发现仍旧无法选择图片。调试之后发现data.getData();为file类型,而之前正常的为content类型。所以改进代码时,便加了个判断。问题得到初步解决。
代码:
private void doPhoto(int requestCode,Intent data)
{
if(requestCode == SELECT_PIC_BY_PICK_PHOTO ) //从相册取图片,有些手机有异常情况,请注意
{
if(data == null)
{
Toast.makeText(this, "请选择本地相册照片", Toast.LENGTH_LONG).show();
return;
}
photoUri = data.getData();
if(photoUri == null )
{
Toast.makeText(this, "请选择本地相册照片", Toast.LENGTH_LONG).show();
return;
}
}
//有的手机是获取的Uri直接就是file对象,比如说红米note,因此此处加一个判断
//如果直接为file对象直接拿到图片路径即可,如果为content对象,则通过以下代码拿到图片路径
String tem = photoUri.toString();
if (tem.startsWith("file")) {
picPath=photoUri.getPath();
}else {
picPath=getPicPath(photoUri);
}
Log.i(TAG, "imagePath = "+picPath);
if(picPath != null && ( picPath.endsWith(".png") || picPath.endsWith(".PNG")|| picPath.endsWith(".jpeg") ||picPath.endsWith(".jpg") ||picPath.endsWith(".JPG")||picPath.endsWith(".gif")||picPath.endsWith(".bmp")
||picPath.endsWith(".tiff")|| picPath.endsWith(".JPEG")))
{
lastIntent.putExtra(KEY_PHOTO_PATH, picPath);
setResult(Activity.RESULT_OK, lastIntent);
finish();
}else{
Toast.makeText(this, "请选择本地相册照片", Toast.LENGTH_LONG).show();
}
}
private String getPicPath(Uri photoUri) {
String[] pojo = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(photoUri, pojo, null, null,null);
if(cursor != null )
{
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
cursor.close();
}
return picPath;
}
另外备注一下:如果手机上选择的图片是单反(比如说佳能)拍的,然后保存到手机上的话,可能会出问题。本人在这个地方纠结了好久没有解决,最后只能跟用户说明,只能上传手机拍摄的图片。个人经验总结,希望能对各位有所借鉴!