【发布时间】:2013-07-11 04:26:50
【问题描述】:
有没有办法检查我作为 URI 加载的文件是 android 中的图像还是视频?我正在尝试将图像和视频动态加载到列表/详细视图的片段中,并且需要将它们区分开来。
【问题讨论】:
标签: android
有没有办法检查我作为 URI 加载的文件是 android 中的图像还是视频?我正在尝试将图像和视频动态加载到列表/详细视图的片段中,并且需要将它们区分开来。
【问题讨论】:
标签: android
我猜最简单的方法是检查扩展名
if ( file.toString().endsWith(".jpg") {
//photo
} else if (file.toString().endsWith(".3gp")) {
//video
}
【讨论】:
toLowerCase() 什么都不说;-)
如果您从内容解析器获取 Uri,则可以使用 getType(Uri); 获取 mime 类型;
ContentResolver cR = context.getContentResolver();
String type = cR.getType(uri);
应该返回类似于“image/jpeg”的东西,你可以检查你的显示逻辑。
【讨论】:
我会检查 mimeType,然后检查它是否对应于图像或视频。
检查文件路径是否为图像的完整示例如下:
public static boolean isImageFile(String path) {
String mimeType = URLConnection.guessContentTypeFromName(path);
return mimeType != null && mimeType.startsWith("image");
}
对于视频:
public static boolean isVideoFile(String path) {
String mimeType = URLConnection.guessContentTypeFromName(path);
return mimeType != null && mimeType.startsWith("video");
}
【讨论】:
通过ContentResolver(如jsrssoftwareanswer)检查类型似乎是最合适的。不过,在某些情况下,这可能会返回 null。
在这种情况下,我最终尝试将流解码为位图以确认它在图像中(但仅解码边界,因此速度非常快且不占用太多内存)。
我的图像测试器辅助函数如下所示:
public static boolean checkIsImage(Context context, Uri uri) {
ContentResolver contentResolver = context.getContentResolver();
String type = contentResolver.getType(uri);
if (type != null) {
return type.startsWith("image/");
} else {
// try to decode as image (bounds only)
InputStream inputStream = null;
try {
inputStream = contentResolver.openInputStream(uri);
if (inputStream != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
return options.outWidth > 0 && options.outHeight > 0;
}
} catch (IOException e) {
// ignore
} finally {
FileUtils.closeQuietly(inputStream);
}
}
// default outcome if image not confirmed
return false;
}
对于视频,可以采用类似的方法。我不需要它,但我相信MediaMetadataRetriever 可用于验证流是否包含有效视频,以防type 检查失败。
【讨论】: