2017-10-15 120 views
0

这是我曾经让我的形象的URI Uri imageUri = data.getData();从uri获取实际路径?

如何获得图像的实际路径选择的代码?

的URI值/我目前得到的路径是

内容://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FLightStick%2F144pixels.bmp

,我需要的是我的其他功能图像的正确filepath是

/storage/emulated/0/LightStick/144pixels.bmp

图像选择功能:

其从先前的函数使用imageUri上传功能。 String path = imageUri.getPath().toString();应用程序崩溃,去到一个活套文件时在调试

public void onUploadToArduino(){ 
    String path = imageUri.getPath().toString();//<- app crashes and goes to a looper file when in debug 
    String sdpath = System.getenv("EXTERNAL_STORAGE"); 
    String extStore = Environment.getExternalStorageDirectory().getPath(); 
    String FILENAME = extStore + "/LightStick/144pixels.bmp"; 

    String collected = null; 
    FileInputStream fis = null; 

    FileInputStream fileInputStream = null; 
    byte[] bytesArray = null; 

    try { 
     File file = new File(FILENAME);//<- this works 
     //File file = new File(path);//<- this doesnt 
     bytesArray = new byte[(int) file.length()]; 

     //read file into bytes[] 
     fileInputStream = new FileInputStream(file); 
     fileInputStream.read(bytesArray); 
+0

您是否检查过[this](https://stackoverflow.com/a/13209522/2591002)和[this](https://stackoverflow.com/a/8892463/2591002)? –

+2

[从mediastore的URI获取文件名和路径]的可能副本(https://stackoverflow.com/questions/3401579/get-filename-and-path-from-uri-from-mediastore) –

+0

@SweetWisherツ:所有三个您的链接集中在有问题的解决方案上。例如,他们都不会处理问题中的“Uri”。 – CommonsWare

回答

2

如何获得所选图像的实际路径?

你不知道。 A Uri不是文件,可能不指向文件,更不用说可以访问的文件。

使用ContentResolveropenInputStream()得到Uri标识的内容InputStream。理想情况下,只需使用流。如果你需要一些其他的API一个File是写得不好,不支持流:

  • 创建一些File自己控制的FileOutputStream(例如,在getCacheDir()

  • 使用InputStream和该FileOutputStream到字节复制到文件

  • 使用您的文件

相关问题