Unable to get the image path from whatsapp share URI

Suseendran Kandasamy picture Suseendran Kandasamy · Nov 3, 2017 · Viewed 75.3k times · Source
Uri = content://com.whatsapp.provider.media/item/118727

I'm not able to get the actual path from this URI

Answer

Shubham Srivastava picture Shubham Srivastava · Mar 30, 2018

Following the Documentation , i receive the image intent through :

void onCreate (Bundle savedInstanceState) {
    ...
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            handleSendImage(intent); // Handle single image being sent
        }
    } 
}

ContentResolver wasn't working in this case as "_data" field was returning null. So i found another way to get a file from content URI.

In handleSendImage() you need to open inputStream and then copy it into a file.

void handleSendImage(Intent intent) throws IOException {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
      File file = new File(getCacheDir(), "image");
      InputStream inputStream=getContentResolver().openInputStream(imageUri);
      try {

        OutputStream output = new FileOutputStream(file);
        try {
          byte[] buffer = new byte[4 * 1024]; // or other buffer size
          int read;

          while ((read = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, read);
          }

          output.flush();
        } finally {
          output.close();
        }
      } finally {
        inputStream.close();
        byte[] bytes =getFileFromPath(file);
        //Upload Bytes.
      }
    }
  }

getFileFromPath() gets you the bytes which you can upload on your server.

  public static byte[] getFileFromPath(File file) {
    int size = (int) file.length();
    byte[] bytes = new byte[size];
    try {
      BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
      buf.read(bytes, 0, bytes.length);
      buf.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return bytes;
  }