摄像头捕获后,获取存储在库中的图像的路径

时间:2014-12-05 10:05:56

标签: android android-image

我正在使用以下代码打开相机

Intent captureImageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

cordova.setActivityResultCallback(this);

cordova.getActivity().startActivityForResult(captureImageIntent,RESULT_CAPTURE_IMAGE);

onActivityResult内部我正在尝试获取存储在图库中的path of the image,以便我可以将其返回到网页。

这是我到目前为止所尝试的

Uri uri = intent.getData(); // doesnt work 

我尝试使用MediaStore.EXTRA_OUTPUT,但在这种情况下,我的意图是空的。

captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);

所以有人能告诉我如何获取路径?

修改

 String fileName = "temp.jpg";  
 contentValues values = new ContentValues();  
 values.put(MediaStore.Images.Media.TITLE, fileName); 

            Uri mPhotoUri = cordova.getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);  

1 个答案:

答案 0 :(得分:1)

定义设置和获取捕获图像路径的自定义方法:

private String imgPath;

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

public String getImagePath() {
   return imgPath;
}

使用捕获意图将图像uri设置为EXTRA_OUTPUT:

captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());

从解码的捕获图像路径获取捕获的图像位:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (resultCode == Activity.RESULT_OK) {
       if (requestCode == RESULT_CAPTURE_IMAGE) {
           imgUserImage.setImageBitmap(decodeFile(getImagePath()));
       }
   }
}

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;
}