Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Get MIME type from file without extension

As far as I'm aware there's only three ways to get the MIME type from reading the existing questions.

1) Determining it from the file extension using MimeTypeMap.getFileExtensionFromUrl

2) "Guess" using the inputStream with URLConnection.guessContentTypeFromStream

3) Using the ContentResolver to get the MIME type using content Uri (content:\) context.getContentResolver().getType

However, I only have the file object, with the obtainable Uri being the file path Uri (file:). The file does not have an extension. Is there still a way to get the MIME type of the file? Or a way to determine the content Uri from the file path Uri?

like image 535
Jason Hu Avatar asked Sep 06 '13 19:09

Jason Hu


1 Answers

Have you tried this? It works for me (only for image files).

public static String getMimeTypeOfUri(Context context, Uri uri) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    /* The doc says that if inJustDecodeBounds set to true, the decoder
     * will return null (no bitmap), but the out... fields will still be
     * set, allowing the caller to query the bitmap without having to
     * allocate the memory for its pixels. */
    opt.inJustDecodeBounds = true;

    InputStream istream = context.getContentResolver().openInputStream(uri);
    BitmapFactory.decodeStream(istream, null, opt);
    istream.close();

    return opt.outMimeType;
}

Of course you can also use other methods, such as BitmapFactory.decodeFile or BitmapFactory.decodeResource like this:

public static String getMimeTypeOfFile(String pathName) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathName, opt);
    return opt.outMimeType;
}

It will return null if failed to determine the MIME type.

like image 141
fikr4n Avatar answered Sep 27 '22 18:09

fikr4n