如何使用Content Resolver从图库中的图像获取路径数据

时间:2018-10-22 08:12:13

标签: android imageview android-contentresolver

我已经成功地从图库中获取了图像,但是由于文件为空,因此无法将图像上传到服务器。我想添加任何代码吗?我添加了imageView.getPath,但是我只获取了从摄像机图像到服务器的路径,并从图库中获取了空图像。

我得到了这个路径,content://com.android.providers.media.documents/document/image%3A5755 但仍然无法上传到服务器

private void getImageFromGallery(Intent data) {

    mSelectedImgURI = data.getData();

    mimeType = getImageExt(mSelectedImgURI);
    uploadDialog.dismiss();

    imgCategory.setImageURI(mSelectedImgURI);
}

private void getImageFromCamera(Intent data) {

    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    String tempFileName = System.currentTimeMillis() + ".jpg";
    File destination = new File(Environment.getExternalStorageDirectory(),tempFileName);
    FileOutputStream fo;

    try {

        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();

        mSelectedImgURI = Uri.fromFile(destination);
        uploadDialog.dismiss();
        imgCategory.setImageBitmap(thumbnail);

    } catch (IOException e) {
        Log.d(TAG, "Internal error - " + e.getLocalizedMessage());
    }
}

public String getImageExt(Uri uri){
    ContentResolver contentResolver = getApplicationContext().getContentResolver();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}

1 个答案:

答案 0 :(得分:0)

这是我通常使用的方法

 public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

这将返回文件位置,您可以通过调用获取文件

File realFile = new File(getRealPathFromURI(mSelectedImgUri));