gpt4 book ai didi

java - 从 Uri.fromFile(file) 得到的 URI 格式和普通的 URI 格式不一样?

转载 作者:行者123 更新时间:2023-11-30 01:47:48 30 4
gpt4 key购买 nike

我正在尝试检索文件的 URI。该文件存储在:

/storage/emulated/0/AppName/FileName.png

如果我使用 Uri.fromFile(file),我得到的是

file:///storage/emulated/0/AppName/FileName.jpg

我想要的是这种格式的东西:

content://media/external/images/media/51128? 

为什么 Uri.fromFile(file) 不给我这个?我怎样才能得到这个?

最佳答案

Uri.fromFile() 给出文件 URI,而不是内容 URI,这正是您想要的。

至于如何得到这个,我建议你看this answer因为它涵盖了从内容 URI 到内容 URI 的转换。

相关代码,稍作修改以匹配您的媒体类型(图片):

/**
* Gets the MediaStore video ID of a given file on external storage
* @param filePath The path (on external storage) of the file to resolve the ID of
* @param contentResolver The content resolver to use to perform the query.
* @return the video ID as a long
*/
private long getImageIdFromFilePath(String filePath,
ContentResolver contentResolver) {


long imageId;
Log.d(TAG,"Loading file " + filePath);

// This returns us content://media/external/images/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")

Uri imagesUri = MediaStore.Images.getContentUri("external");

Log.d(TAG,"imagesUri = " + imagessUri.toString());

String[] projection = {MediaStore.Images.ImageColumns._ID};

// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(imagesUri, projection, MediaStore.Images.ImageColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(projection[0]);
imageId = cursor.getLong(columnIndex);

Log.d(TAG,"Image ID is " + imageId);
cursor.close();
return imageId;
}

关于java - 从 Uri.fromFile(file) 得到的 URI 格式和普通的 URI 格式不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33461211/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com