24

有没有办法检查我作为 URI 加载的文件是 android 中的图像还是视频?我正在尝试将图像和视频动态加载到列表/详细视图的片段中,并且需要将它们区分开来。

4

4 回答 4

79

我会检查 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");
}
于 2015-06-07T16:55:05.917 回答
13

如果您从内容解析器获取 Uri,则可以使用 getType(Uri); 获取 mime 类型;

ContentResolver cR = context.getContentResolver();
String type = cR.getType(uri); 

应该得到类似于“image/jpeg”的东西,你可以检查你的显示逻辑。

于 2013-07-12T15:20:20.600 回答
3

It seems most proper to check type via ContentResolver (as in jsrssoftware answer). Although, this may return null in some cases.

In such case, I ended up trying to decode stream as Bitmap to confirm it is in image (but only decoding bounds, so it's quite fast and not much memory-consuming).

My image-tester helper function looks like this:

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

For videos, one could do similar approach. I did not need it, but I believe MediaMetadataRetriever could be used to verify if stream contains valid video in case type check fails.

于 2018-03-08T14:53:36.233 回答
-51

我猜最简单的方法是检查扩展名

if ( file.toString().endsWith(".jpg") {
//photo
} else if (file.toString().endsWith(".3gp")) {
//video
}
于 2013-07-12T15:16:03.963 回答