2017-04-14 166 views
0

我想从相册中获取图像,但是当我选取任何图片时,它不会显示并停止。我用我的手机测试,我认为问题可能是我用我的代码设置了错误的路径。但我找不到它在哪里。 案例100:采取图片行动,它可以工作,案例101:挑选图片行动。从路径获取图像

这是我的onActivityResult

protected void **onActivityResult**(int requestCode , int resultCode , Intent 
data) 
{ 
    super.onActivityResult(requestCode, resultCode, data); 

    if (resultCode == Activity.RESULT_OK) { 
      switch (requestCode) 
      { 
       case 100: 
        Intent it = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
        sendBroadcast(it); 
        break; 
       case 101: 
        imgUri = convertUri(data.getData()); 

        break; 
      } 
     showImg(); 
    } 
    else { 
     Toast.makeText(this , requestCode==100? "no take the pic" : "no choose the pic" , Toast.LENGTH_LONG).show(); 
    } 
} 

这是我converUri

Uri convertUri(Uri uri){ 
    if(uri.toString().substring(0,7).equals("content")) 
    { 
     String[] colName = {MediaStore.MediaColumns.DATA}; 
     Cursor cursor = getContentResolver().query(uri,colName,null,null,null); 
     cursor.moveToFirst(); 
     uri = Uri.parse("file://"+ cursor.getString(0)); 
    } 
    return uri; 
} 

这是我showImag

void showImg(){ 
    imv = (ImageView) findViewById(R.id.imageView); 
    int iw ,ih , vw, vh; 
    boolean needRotate; 
    BitmapFactory.Options option = new BitmapFactory.Options(); 
    option.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(imgUri.getPath(),option); 

    iw = option.outWidth; 
    ih = option.outHeight; 
    vw = imv.getWidth(); 
    vh = imv.getHeight(); 

    int scaleFactor; 
    if(iw<ih) 
    { 
     needRotate = false; 
     scaleFactor = Math.min(iw/vw , ih/vh); 
    }else{ 
     needRotate = true ; 
     scaleFactor =Math.min(ih/vw , iw/vh); 
    } 
    option.inJustDecodeBounds = false; 
    option.inSampleSize = scaleFactor ; 
    Bitmap bmp = BitmapFactory.decodeFile(imgUri.getPath(),option); 
    if(needRotate) 
    { 
     Matrix matrix = new Matrix(); 
     matrix.postRotate(90); 
     bmp = Bitmap.createBitmap(bmp , 0 , 0 ,bmp.getWidth(), bmp.getHeight(), matrix , true); 
    } 
    imv.setImageBitmap(bmp); 
} 

回答

0

你在试图让一个文件系统错误的方法路径。

更好地使用onActivityResult的data.getData()uri dirtectly。

Bitmap bmp = BitmapFactory.decodeFile(imgUri.getPath(),option); 

更改为:

InputStream is = getContentResolver().openInputStream(data.getData()); 
Bitmap bmp = BitmapFactory.decodeStream(is, option); 

执行相同的第一个电话。您只能使用is一次。

+0

你的答案,但它不能工作。当我选择时,它停止。是否我的convertUri或我的手机或使用权限有问题。 –