如何在android中获取捕获图像的路径

Posted

技术标签:

【中文标题】如何在android中获取捕获图像的路径【英文标题】:How to get path of a captured image in android 【发布时间】:2014-01-18 08:17:53 【问题描述】:

我正在开发一个安卓应用程序。它具有捕获的图像应显示在屏幕上的功能,我需要获取该图像路径,以便我可以将该图像发送到服务器。

我可以在屏幕上显示图像,但无法获取绝对图像路径。

我得到的路径如下:

content://media/external/images/media/1220
content://media/external/images/media/1221

如何获取实际的图片路径?

这是我的代码:

mintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mintent.putExtra(MediaStore.EXTRA_OUTPUT,
                 MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
startActivityForResult(mintent, 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
  super.onActivityResult(requestCode, resultCode, data);
  if ((data != null && !data.toString().equalsIgnoreCase("Intent   "))
      || requestCode == 1)
    switch (requestCode) 
      case 1:
        try 
          // Uri imageFileUri = data.getData();
          // String path=getRealPathFromURI(this,imageFileUri);
          // Bitmap bitmap = (Bitmap) data.getExtras().get("data");

          String photoPath = null;
          Bitmap bitmap = (Bitmap) data.getExtras().get("data");
          Intent intent = new Intent(this, Media.class);
          intent.putExtra("BitmapImage", bitmap);

          Bundle b = mintent.getExtras();
          if (b != null && b.containsKey(MediaStore.EXTRA_OUTPUT))  // large
            // image?
            String timeStamp = new SimpleDateFormat(
                "yyyyMMdd_HHmmss").format(new Date());
            // Shouldn't have to do this ... but
            photoPath = MediaStore.Images.Media.insertImage(
                        getContentResolver(), bitmap, "Img" + timeStamp
                        + ".jpeg", null);
          
        
    

photoPath的值如上所示。

如何从该路径获取我的绝对图像路径。

【问题讨论】:

【参考方案1】:

这是一个工作函数--

String selectedImagePath = getPath(selectedImageUri);

private String getPath(Uri uri) 

    String[] projection =  MediaStore.Images.Media.DATA ;
    Cursor cursor = getContentResolver().query(uri, projection, null, null,null);

    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();

    return cursor.getString(column_index);

【讨论】:

我不能从“content://media/external/images/media/1220”获取路径吗? 选择了什么ImageUri 如何获取URI 这是捕获的图像的 Uri。【参考方案2】:

完整的工作解决方案

final private int PICK_IMAGE = 1;
    final private int CAPTURE_IMAGE = 2;
private String imgPath;

btnGallery.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View v) 
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);

            
        );

        btnCapture.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View v) 
                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            
        );


public Uri setImageUri() 
        // Store image in dcim
        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
        Uri imgUri = Uri.fromFile(file);
        this.imgPath = file.getAbsolutePath();
        return imgUri;
    


    public String getImagePath() 
        return imgPath;
    


@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        if (resultCode != Activity.RESULT_CANCELED) 
            if (requestCode == PICK_IMAGE) 
                selectedImagePath = getAbsolutePath(data.getData());
                imgUser.setImageBitmap(decodeFile(selectedImagePath));
             else if (requestCode == CAPTURE_IMAGE) 
                selectedImagePath = getImagePath();
                imgUser.setImageBitmap(decodeFile(selectedImagePath));
             else 
                super.onActivityResult(requestCode, resultCode, data);
            
        

    

public String getAbsolutePath(Uri uri) 
        String[] projection =  MediaColumns.DATA ;
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) 
            int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
         else
            return null;
    

public Bitmap decodeFile(String path) 
        try 
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 70;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
         catch (Throwable e) 
            e.printStackTrace();
        
        return null;

    

【讨论】:

为什么没有人接受这个答案......非常感谢 Biraj......我发现的最神奇的解决方案......继续......!!! managedQuery 需要五个参数作为Cursor cursor = managedQuery(uri, projection, null, String[], null); 你已经传递了 null 所以它给出错误任何想法?【参考方案3】:

这样试试,

    void onActivityResult(int requestCode, int resultCode, Intent data)   
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) 
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
    
            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
            Uri tempUri = getImageUri(getApplicationContext(), photo);
    
            // CALL THIS METHOD TO GET THE ACTUAL PATH
            File finalFile = new File(getRealPathFromURI(tempUri));
    
            System.out.println(mImageCaptureUri);
          
    
    
    public Uri getImageUri(Context inContext, Bitmap inImage) 
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    
    
    public String getRealPathFromURI(Uri uri) 
        String path = "";
        if (getContentResolver() != null) 
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if (cursor != null) 
                cursor.moveToFirst();
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                path = cursor.getString(idx);
                cursor.close();
            
        
        return path;
    

【讨论】:

【参考方案4】:

在相机按钮上

        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

        File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));


        try 

            intent.putExtra("return-data", true);

            startActivityForResult(intent, CAMERA_REQUEST);
             catch (ActivityNotFoundException e) 
            // Do nothing for now
            

并在活动结果上写入

 protected void onActivityResult(int requestCode, int resultCode, Intent data) 

             if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)   
              // Bitmap photo1 = (Bitmap) data.getExtras().get("data");
                 File file1 = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
                   Bitmap bitmap11 = decodeSampledBitmapFromFile(file1.getAbsolutePath(), 500, 300);
                  // 
                      
    

【讨论】:

以上是关于如何在android中获取捕获图像的路径的主要内容,如果未能解决你的问题,请参考以下文章

如何在Android中将exif数据写入图像?

在Android中的远程数据库中插入图像路径

如何在REALM中存储捕获的图像路径? [关闭]

如何在android中使用相机捕获自定义图像大小?

如何等到相机在android中捕获图像?

如何在存储 SD 卡之前裁剪捕获的图像? [复制]