如何从Gallery获取图像URI

时间:2015-09-18 13:04:06

标签: android

我需要从图库中提取图像。我可以打开图库来选择图像,但在选择图像后它不会返回任何内容。我需要将fileUri发送到另一个活动并将其显示在ImageView上。 我可以做这个相机,就像按钮点击它调用相机然后我捕获图像并将其发送到另一个活动。

但我不明白我用于画廊的内容。有人请帮帮我。

更新

  

这是我用来从相机

获取图像
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
  

这是用于从图库中获取图像   但我想以与我为captureImage()做的相同的方式做到这一点,这样我就可以将ImageUri发送到其他活动

 private void browseImage(){
    try {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
         fileUri = getOutputMediaFileUri(PICK_IMAGE);//this is m using for camera 
         Log.w("ImageAddressOnClick pr", ""+fileUri);
        startActivityForResult(galleryIntent, GALLERY_IMAGE_PICK);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
        e.getMessage()+"ye show hora h",
        Toast.LENGTH_LONG).show();
        Log.e(e.getClass().getName(), e.getMessage(), e);
    }
  

OnActivityResult方法

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
     super.onActivityResult(requestCode, resultCode, data);



    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            // successfully captured the image
            // launching upload activity
            launchUploadActivity(true);


        } else if (resultCode == RESULT_CANCELED) {

            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }


    }
    else if(requestCode == GALLERY_IMAGE_PICK && resultCode == RESULT_OK
            && null != data)
            {
       Uri selectedImage = data.getData();
         String[] filePathColumn = { MediaStore.Images.Media.DATA };
         Log.w("onActivityResult", "chali ye onActivityResult "+selectedImage);
         // Get the cursor
         Cursor cursor = getContentResolver().query(selectedImage,
                 filePathColumn, null, null, null);
         // Move to first row
         cursor.moveToFirst();

         //int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
       //  imgDecodableString = cursor.getString(columnIndex);
         cursor.close();
         launchUploadActivity(true);
            }
          }

private void launchUploadActivity(boolean isImage){
    Intent i = new Intent(MainActivity.this, UploadActivity.class);
    i.putExtra("filePath", fileUri.getPath());
    i.putExtra("isImage", isImage);
    startActivity(i);
}

/**
 * ------------ Helper Methods ---------------------- 
 * */

/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}
  

我通过launchUploadActivity();

发送数据

提前致谢:)

4 个答案:

答案 0 :(得分:6)

更改onActivityResult:

else if(requestCode == GALLERY_IMAGE_PICK && resultCode == RESULT_OK
        && null != data)
        {
            Uri selectedImage = data.getData();         
            String picturePath = getRealPathFromURI(selectedImage,
                    this);
           Intent i = new Intent(MainActivity.this, UploadActivity.class);
           i.putExtra("filePath", selectedImage);
           i.putExtra("isImage", isImage);
           startActivity(i);
        }
      }
}


public String getRealPathFromURI(Uri contentURI, Activity context) {
        String[] projection = { MediaStore.Images.Media.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = context.managedQuery(contentURI, projection, null,
                null, null);
        if (cursor == null)
            return null;
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        if (cursor.moveToFirst()) {
            String s = cursor.getString(column_index);
            // cursor.close();
            return s;
        }
        // cursor.close();
        return null;
    }

答案 1 :(得分:0)

//handling the image chooser activity result
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath1 = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(.getContentResolver(), filePath1);
            profilePic.setImageBitmap(bitmap);
            uploadProfilePic(filePath1);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

从uri获取文件路径。

  public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

答案 2 :(得分:-1)

HI使用它从您的图库中获取路径。

private void openCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
    String currentTimeStamp = dateFormat.format(new Date());
    f = new File(android.os.Environment.getExternalStorageDirectory(), currentTimeStamp);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
    startActivityForResult(intent, 1);
}

private void openGallery() {
    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(Intent.createChooser(intent, "Select File"), REQUEST_GALLERY);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            try {
                String click = f.getAbsolutePath();
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(User_Detail.KEY_ALBUM_IMAGE_PATH, click);
                values.put(User_Detail.USER_ID, Utlity.user_id);
                values.put(User_Detail.KEY_ID_ALBUM_REF, album_id);
                long loginStat = db.insert(User_Detail.TABLE_4, null, values);
                loadData(album_id);

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (requestCode == 2) {

            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            picturePath = c.getString(columnIndex);
            if (picturePath != null && picturePath.length() > 1) {
                ContentValues va = new ContentValues();
            } else {
            }
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            String image_path = picturePath;
            ContentValues values = new ContentValues();
            values.put(User_Detail.KEY_ALBUM_IMAGE_PATH, image_path);
            values.put(User_Detail.USER_ID, Utlity.user_id);
            values.put(User_Detail.KEY_ID_ALBUM_REF, album_id);
            long loginStat = db.insert(User_Detail.TABLE_4, null, values);
            loadData(album_id);
            c.close();
            Log.w("path of image from gallery......******************.........", picturePath + "");
        }
    }
}

答案 3 :(得分:-1)

试试这个,  写在你的onActivityResult()方法

if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
}
}

这是getRealPathFromURI()方法。

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}