【问题标题】:How to get path data from image in gallery by using Content Resolver如何使用 Content Resolver 从图库中的图像中获取路径数据
【发布时间】:2018-10-22 08:12:12
【问题描述】:

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

我得到了这个路径,内容://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));
}

【问题讨论】:

标签: android imageview android-contentresolver


【解决方案1】:

这是我常用的一种方法

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

【讨论】:

  • 这个答案应该有很多赞,它可以工作
猜你喜欢
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
相关资源
最近更新 更多