2012-03-09 41 views
10

我从库取出一个图像的Uri的使用乌里之后,从画廊ACTION_GET_CONTENT不setImageURI ImageView的

Intent intent = new Intent(); 
intent.setType("image/*"); 
intent.setAction(Intent.ACTION_GET_CONTENT); 
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), requestCode); 

工作(),并试图通过

imageView.setImageURI(uri); 

这里显示的图像返回,uri是通过intent.getData()在onActivityResult中接收的图像的Uri。

但没有图像显示。另外,对于

File file=new File(uri.getPath()); 

file.exists()返回false。

+0

你是否检查uri值..日志和检查..粘贴在这里的uri – Ronnie 2012-04-22 13:13:37

回答

22

问题是,你得到的Uri,但从该URI你必须创建位图显示在你的ImageView。这个代码有各种机制可以做同样的工作。

Intent intent = new Intent(); 
intent.setType("image/*"); 
intent.setAction(Intent.ACTION_GET_CONTENT); 
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), 1); 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if(resultCode==RESULT_CANCELED) 
    { 
     // action cancelled 
    } 
    if(resultCode==RESULT_OK) 
    { 
     Uri selectedimg = data.getData(); 
     imageView.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedimg)); 
    } 
} 
+0

其工作对我..谢谢:) – 2016-12-13 13:15:38

0

启动所述图库选配

Intent intent = new Intent(); 
// Show only images, no videos or anything else 
intent.setType("image/*"); 
intent.setAction(Intent.ACTION_GET_CONTENT); 
// Always show the chooser (if there are multiple options available) 
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); 

PICK_IMAGE_REQUEST是定义为一个实例变量的请求代码。

private int PICK_IMAGE_REQUEST = 1; 

显示在活动所选图像/片段

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

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { 

     Uri uri = data.getData(); 

     try { 
      Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); 
      // Log.d(TAG, String.valueOf(bitmap)); 

      ImageView imageView = (ImageView) findViewById(R.id.imageView); 
      imageView.setImageBitmap(bitmap); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

您的布局需要有这样一个ImageView的:

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/imageView" />