android - 无法从 whatsapp 共享 URI 获取图像路径

标签 android image uri media whatsapp

Uri = content://com.whatsapp.provider.media/item/118727

我无法从此 URI 获取实际路径

最佳答案

Documentation 之后,我通过以下方式接收图像 Intent :

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 在这种情况下不起作用,因为“_data”字段返回空值。所以我找到了另一种从内容 URI 获取文件的方法。

handleSendImage()中你需要打开inputStream然后复制到一个文件中。

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() 获取您可以上传到服务器的字节数。

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

关于android - 无法从 whatsapp 共享 URI 获取图像路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47091040/

相关文章:

jquery - 如何在 jQuery 或 CSS 中为此 Accordion 切换图像 onclick?

arrays - 快速创建图像数组

java - 从其他应用打开 Tumblr 应用上的博客

c# - 从 Uri.Segment.Last() 中删除结束斜线?

android - 如何在 Android 中使用默认动画?

java - UI不会自动更新,只有刷新后才会改变

android - 在 Android 系统浏览器中打开 swf 而不是在 Phonegap 中

android - Android 10 (api 29) 中没有这样的文件或目录

python - PyQT4 和 QPixmap : load image with size zero?

android - Android平台URI的构建原则是什么?