44

I want to get as string the image extension (for example "jpg", "png", "bmp" ecc.) of the images loaded from the gallery or picked from the camera.

I have used a method in this form to load images from the gallery

    private static final int SELECT_PICTURE_ACTIVITY_REQUEST_CODE = 0;
....
private void selectPicture() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, SELECT_PICTURE_ACTIVITY_REQUEST_CODE);
}
....
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
        case SELECT_PICTURE_ACTIVITY_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = imageReturnedIntent.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String filePath = cursor.getString(columnIndex);
                    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                    .........
                }
                cursor.close();
            }
            break;
    }
}
AndreaF
  • 11,975
  • 27
  • 102
  • 168

11 Answers11

76
 filePath.substring(filePath.lastIndexOf(".")); // Extension with dot .jpg, .png

or

 filePath.substring(filePath.lastIndexOf(".") + 1); // Without dot jpg, png
razz
  • 9,770
  • 7
  • 50
  • 68
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
44

I know it's pretty late but for those who still have a problem when getContentResolver().getType(uri) returns null when path contains white spaces. This also solves the problem when an image is opened via File Manager instead of gallery. This method returns the extension of the file (jpg, png, pdf, epub etc..).

 public static String getMimeType(Context context, Uri uri) {
    String extension;

    //Check uri format to avoid null
    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        //If scheme is a content
        final MimeTypeMap mime = MimeTypeMap.getSingleton();
        extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
    } else {
        //If scheme is a File
        //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());

    }

    return extension;
}
Aaron
  • 1,256
  • 11
  • 16
  • 1
    String mimeType = context.getContentResolver().getType(uri); //get value: "image/jpg"; String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); // get null – gelosie Sep 29 '16 at 09:54
  • Turning a file Uri to a File and then to a Uri again is a bit redundant. – Eugen Pechanec Feb 13 '17 at 12:32
  • Because I need to parse spaces and special characters i.e space should be %20. Using new File() on the uri path will automatically parse those special characters. If you remove this part, this code will throw an error on file names that have spaces or special characters – Aaron Feb 27 '21 at 01:19
19
getContentResolver().getType(theReceivedUri);

The above snippet gets you the type as "media/format"

Anand
  • 321
  • 2
  • 4
9

Dear Friend we can find the extension of any file, image, video and any docs. for this.

First, we will create a method GetFileExtension which we want to call to find the extension of a file, image, data and docs. Here I took a variable named:

Uri videouri = data.getData();

in OnActivity Result then I invoke it in,

onclick(View view)
{
    GetFileExtension(videouri);
    Toast.makeText(this, "Exten: "+GetFileExtension(videouri), Toast.LENGTH_SHORT).show();
}

Now make a Class to class GetFileExtension:

// Get Extension
public String GetFileExtension(Uri uri)
{
        ContentResolver contentResolver=getContentResolver();
        MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();

        // Return file Extension
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}

Due to this method we can find out the extension of any file in java and in android. I'm 100 % sure it will work for you all who are making corporate App. If you like then vote for me..

pushkin
  • 9,575
  • 15
  • 51
  • 95
Pradeep Sheoran
  • 493
  • 6
  • 15
8

you have multiple choice to get extension of file:like:

1-String filename = uri.getLastPathSegment(); see this link

2- you can use this code also

 filePath .substring(filePath.lastIndexOf(".")+1);

but this not good aproch.

3-if you have URI of file then use this Code

String[] projection = { MediaStore.MediaColumns.DATA,
    MediaStore.MediaColumns.MIME_TYPE };

4-if you have URL then use this code

public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
    type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;}
John smith
  • 1,781
  • 17
  • 27
6

For "content://" sheme

fun Uri.getFileExtension(context: Context): String? {
    return MimeTypeMap.getSingleton()
        .getExtensionFromMimeType(context.contentResolver.getType(this))
}
kulikovman
  • 333
  • 4
  • 8
6

I think this should get you to where you want (I haven't tried it, just read a bit around and I think it works).

Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA, 
                           MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor =
     getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor.moveToFirst()) {
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
    int fileNameIndex = cursor.getColumnIndex(filePathColumn[1]);
    String fileName = cursor.getString(fileNameIndex);
    // Here we get the extension you want
    String extension = fileName.replaceAll("^.*\\.", ""); 
    .........
}
cursor.close();
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • No (at least pretty sure). `MediaStore.Images.Media.DISPLAY_NAME` has the filename without extension. The only place in that database that includes the extension is `MediaStore.Images.Media.DATA` – zapl Mar 18 '12 at 12:27
  • The `The data stream for the file`, hmm? Then the documentation is crappy. – Boris Strandjev Mar 18 '12 at 12:29
  • 1
    meh, I am wrong. DISPLAY_NAME has the extension included, TITLE was the column where it is stripped - just checked in the db. In DATA you have the full path. – zapl Mar 18 '12 at 12:35
  • Regarding `DISPLAY_NAME` and `TITLE`: The filename is only used as a [default](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.0.3_r1/com/android/providers/media/MediaProvider.java#2605) value if there is nothing better available (e.g. via `MediaScanner`). The only safe place to get the filename is DATA. That has to be the real filepath. – zapl Mar 18 '12 at 12:49
  • @Boris I have tried to use this code but doesn't work ...the extension string results null – AndreaF Mar 18 '12 at 18:54
0

I think this should use MediaStore.MediaColumns.MIME_TYPE

String[] projection = { MediaStore.MediaColumns.DATA,
        MediaStore.MediaColumns.MIME_TYPE };
laalto
  • 150,114
  • 66
  • 286
  • 303
gianguyen
  • 221
  • 3
  • 7
0

You can split string to strings array and get last index of it

 String[] fileArr = picturePath.split("\\.");
    
 String fileExtension = fileArr[fileArr.length - 1];
0

You can also get it using the Cursor. Here you can get not only the file type

val contentResolver = context.contentResolver

fun setInfoFile(contentResolver: ContentResolver, uri : Uri) {
    val cursor = contentResolver.query(uri, null, null, null, null)
    
    if (cursor != null && cursor.moveToFirst()) {
        val type = contentResolver.getType(uri).toString() // !!! return MIME types
        val fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
        val bytes = cursor.getString(cursor.getColumnIndex(OpenableColumns.SIZE))
        cursor.close()
    }
}

Here's how I get the type from the MIME-type

fun String.getMimeTypeDescription(): String {
    val type =  when (this) {
        "application/msword" -> "doc"
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -> "docx"
        "application/vnd.ms-excel" -> "xls"
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> "xlsx"
        else -> this
    }.split("/")

    return type.last()
}
Segrei Ulanov
  • 141
  • 1
  • 4
0

if you get content://media Uris as result and you want the extension then you have to query the database as you do and extract if from filePath. E.g. with this

To get the filename out of a full path the simplest solution is

String filename = (new File(filePath)).getName();
zapl
  • 63,179
  • 10
  • 123
  • 154