如何将其他应用程序共享的图像Uri转换为文件?

时间:2018-02-15 11:18:01

标签: android

 private void handleImageData(Uri data) {
    if(data != null){
        file = new File(data.getPath());
        capturedImageView.setImageURI(data);
    }
    else {
        AndyUtils.showErrorToast("Invalid Uri", this );
    }
}

我总是将文件视为null。我知道这不是正确的方法。我错过了什么?

1 个答案:

答案 0 :(得分:1)

您应该从InputStream获取Uri,然后将其保存到文件中。这样的事情(代码可能需要一些改进):

File file = new File("path");

//get InputStream
ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream( fileUri );

//write to file
FileOutputStream fos = new FileOutputStream( file );
byte[] buffer = new byte[ 1024 ];
int count;
while ( ( count = is.read( buffer ) ) != -1 ) {
    fos.write( buffer, 0, count );
    fos.flush();
}

//close everything
fos.close();
is.close();