有没有办法在Android中检查我作为URI加载的文件是图像还是视频? 我正在尝试将图像和视频动态加载到片段以进行列表/详细视图,并需要区分它们。
有没有办法在Android中检查我作为URI加载的文件是图像还是视频? 我正在尝试将图像和视频动态加载到片段以进行列表/详细视图,并需要区分它们。
我会检查 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");
}
如果您从内容解析器中获取 Uri,则可以使用 getType(Uri) 获取 MIME 类型。
ContentResolver cR = context.getContentResolver();
String type = cR.getType(uri);
应该得到类似于 "image/jpeg" 的东西,您可以将其与显示逻辑进行检查。Uri uri = Uri.parse(packageLocation+DummyContent.INFO_MAP.get(getArguments().getString(ARG_ITEM_ID)).get(0));
其中info_map是一个(String, ArrayList<String>)对的映射表,get(0)给出文件名,get(1)现在从xml中获取视频类型参数。我希望消除那里需要一个ArrayList来提高性能。如果文件名是vid.p4,get(0)将会给你类似于vid的东西。 - user2532233似乎最适合通过 ContentResolver
检查类型(如 jsrssoftware answer)。但是,在某些情况下,这可能返回 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
检查失败。enum class MediaType {
MediaTypeImage,
MediaTypeVideo,
Unknown
}
fun getMediaType(context: Context, source: Uri): MediaType {
val mediaTypeRaw = context.contentResolver.getType(source)
if (mediaTypeRaw?.startsWith("image") == true)
return MediaType.MediaTypeImage
if (mediaTypeRaw?.startsWith("video") == true)
return MediaType.MediaTypeVideo
return MediaType.Unknown
}
检查的最佳方法是...
图片:
private fun isImage(path: String): Boolean {
val mimeType: String = URLConnection.guessContentTypeFromName(path)
return mimeType.startsWith("image")
}
视频:
private fun isVideo(path: String): Boolean {
val mimeType: String = URLConnection.guessContentTypeFromName(path)
return mimeType.startsWith("video")
}
.zip
或 .rar
:
private fun isZip(name: String): Boolean {
return name.contains(".zip") || name.contains(".rar")
}
我想最简单的方法是检查扩展名
if ( file.toString().endsWith(".jpg") {
//photo
} else if (file.toString().endsWith(".3gp")) {
//video
}
toLowerCase()
了 ;-) - Rick77DISPLAY_NAME
,这可能是文件名,但并不保证。 - hippietrail