Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine Mime type of a uri in android returned by an intent?

First some context of what I am trying to achieve -

I am developing an Image Sharing application for which I need the user to pick an image from the filesystem .

For this , I am using this code -

    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, REQUEST_CODE_IMAGE_PICKER_INTENT);

Now , this triggers a chooser wherein I see multiple options including Gallery and a FileManager App that I have in my phone. If i select gallery and choose an image from there then my Activity receives an Intent with a content uri of an Image. But if I choose the FileManager App , I can choose any file which might not be an image . So , what I need is to be able to determine the mime type of the uri returned in the intent. The intent's getType method returns null .

Is there any way to determine the mime from the returned intent to be able to determine if the content is an image or not .

If this doesn't work this way , then I might have to use MimeTypeMap to determine the mime from the file extension.

like image 281
Vinayak Bhavnani Avatar asked Mar 23 '13 14:03

Vinayak Bhavnani


2 Answers

I found a way to get the mime type of a content uri but nothing worked for other kind of uri's such as uri's of the form 'file://.....' .

To get the mime type of content uri's -

    ContentResolver cr = this.getContentResolver();
    String mime = cr.getType(YOUR_CONTENT_URI);

This works only for content uri's . So for other uri's I am using MimeTypeMap to infer their mime type's from the file extension .

like image 147
Vinayak Bhavnani Avatar answered Sep 28 '22 10:09

Vinayak Bhavnani


if you have URI then you can get mimetype like

Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
String mime = cR.getType(uri);

or try // url = file path or whatever suitable URL you want.

public static String getMimeType(String url)
{
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        type = mime.getMimeTypeFromExtension(extension);
    }
    return type;
}

For more details see these Answers

like image 41
Zar E Ahmer Avatar answered Sep 28 '22 09:09

Zar E Ahmer