从uri获得实际路径?

时间:2017-10-15 12:03:45

标签: android

这是我用来获取我的图像的代码 Uri imageUri = data.getData();

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

我目前获得的Uri值/路径是

  

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

我需要的图像的正确文件路径是我的其他功能

  

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

图像选择功能:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == RESULT_OK){//everything processed successfully
        if(requestCode == IMAGE_GALLERY_REQUEST){ //hearing back from image gallery

            //the address of the image on the SD card
            Uri imageUri = data.getData();
            BMPfilepath =imageUri.getPath();
            //stream to read image data from SD card
            InputStream inputStream;

            try {
                inputStream = getContentResolver().openInputStream(imageUri);//getting an input stream, based no the URI of image
                Bitmap image = BitmapFactory.decodeStream(inputStream);//get bitmap from stream
                imgPicture.setImageBitmap(image);//show image to user in imageview

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show(); //let user know image unavail
            }//catch
        } //requestCode == IMAGE_GALLERY_REQUEST
    }

上传功能,它使用上一个功能中的imageUriString path = imageUri.getPath().toString();应用程序崩溃并在调试时转到looper文件

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

1 个答案:

答案 0 :(得分:2)

  

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

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

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

  • 在您控制的某些FileOutputStream上创建File(例如,在getCacheDir()中)

  • 使用InputStreamFileOutputStream将字节复制到您的文件

  • 使用您的文件