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/