2015-05-11 39 views
3

我发现了很多像我这样的问题的答案,但它们对我来说没有意义。让我解释。Android - 从刚刚拍摄的图片获取URI(不再保存图像)

我有一个ImageButton,让用户拍照并在界面上显示它。当我试图让图像URI,则返回null:

Uri uri = data.getData(); 

我做了一些网络上搜索,发现类似的解决方案:

@Override 
public void onActivityResult(int requestCode, int resultCode, 
     Intent data) { 
    try { 
     if (resultCode == Activity.RESULT_OK) { 
      updateProfilePicure = Boolean.TRUE; 
      switch(requestCode){ 
       case 0: 
        Bundle extras = data.getExtras(); 
        Object xx = data.getData(); 
        Bitmap imageBitmap = (Bitmap) extras.get("data"); 
        Uri tempUri = getImageUri(imageBitmap); 
        imageView.setImageBitmap(imageBitmap); 
        break; 
       default: break; 
      } 
     } 
    } catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 

public Uri getImageUri(Bitmap inImage) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    String path = MediaStore.Images.Media.insertImage(
      ApplicationContext.getInstance().getContext().getContentResolver(), inImage, 
    "Title", null); 
    return Uri.parse(path); 
} 

对我来说,没有任何意义,因为当呼叫转到方法onActivityResult(),图片已保存在DCIM文件夹中,没有任何理由再次保存。那我为什么要用它?

是否有可能找到另一种方式从捕获的图像检索URI?

提前致谢。

+1

那要看情况。如果您在启动相机意图时未添加文件,那么您将无法获得文件Uri,“数据”将返回位图。 – inmyth

回答

5

图片已保存在DCIM文件夹中,没有任何理由再次保存。

不一定。引用the documentation for ACTION_IMAGE_CAPTURE

调用者可能会传递额外的EXTRA_OUTPUT来控制此图像将写入的位置。如果EXTRA_OUTPUT不存在,则在额外字段中将小图像作为位图对象返回。

(以下简称“附加域”在这里键入作为data额外)

你粘贴被检索data额外的代码片段,所以图像不存储。

是否有可能找到另一种方式从捕获的图像检索URI?

你已经有这个代码,在你的第一个代码段 - 如果你在你的ACTION_IMAGE_CAPTURE请求指定UriEXTRA_OUTPUT,你会得到一个Uri回到那个拍摄于Intent手图像到onActivityResult()

2

看看这个链接:http://developer.android.com/training/camera/photobasics.html

我做了很多与图片上的我的最后一个项目。当使用像这样拍图片:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
if (takePictureIntent.resolveActivity(getPackageManager()) != null) 
{ 
    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); 
} 

图像不会被保存(至少它不会在我的项目做到这一点)。您可以直接使用此代码得到一个缩略图:

Bundle extras = data.getExtras(); 
Bitmap imageBitmap = (Bitmap) extras.get("data"); 

如果你想拥有全尺寸的图像,你应该保存它:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
// Ensure that there's a camera activity to handle the intent 
if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
    // Create the File where the photo should go 
    File photoFile = null; 
    try { 
     // This is where the file is created, create it as you wish. For more information about this, see the link or add a comment 
     photoFile = createImageFile(); 
    } catch (IOException ex) { 
     // Error occurred while creating the File 
     ... 
    } 
    // Continue only if the File was successfully created 
    if (photoFile != null) { 
     takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
       Uri.fromFile(photoFile)); 
     startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); 
    } 
} 
相关问题