Get the file extension from images picked from gallery or camera, as string
Asked Answered
N

11

45

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;
    }
}
Novanovaculite answered 18/3, 2012 at 12:5 Comment(1)
I found the latest update and the right answer here: https://mcmap.net/q/76303/-how-i-can-get-the-mime-type-of-a-file-having-its-uriMozza
H
76
 filePath.substring(filePath.lastIndexOf(".")); // Extension with dot .jpg, .png

or

 filePath.substring(filePath.lastIndexOf(".") + 1); // Without dot jpg, png
Hyperbolism answered 18/3, 2012 at 12:25 Comment(3)
after String filePath = cursor.getString(columnIndex);Hyperbolism
I have tried with no success... what is exactly "strname"?? Could you give me more details looking the method that I have used?? Thanks.Novanovaculite
see my updated answer and also see for .jpg or jpg...and check if(null!=filepath&&filepath.trim().lenght()!=0){...}Hyperbolism
S
46

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;
}
Satyriasis answered 9/4, 2016 at 9:7 Comment(3)
String mimeType = context.getContentResolver().getType(uri); //get value: "image/jpg"; String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); // get nullBlen
Turning a file Uri to a File and then to a Uri again is a bit redundant.Wyatt
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 charactersSatyriasis
G
20
getContentResolver().getType(theReceivedUri);

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

Greyhound answered 12/5, 2017 at 6:34 Comment(0)
C
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..

Chartulary answered 12/6, 2018 at 19:41 Comment(0)
N
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;}
Norvil answered 25/8, 2015 at 5:9 Comment(0)
A
7

For "content://" sheme

fun Uri.getFileExtension(context: Context): String? {
    return MimeTypeMap.getSingleton()
        .getExtensionFromMimeType(context.contentResolver.getType(this))
}
Aplomb answered 13/5, 2021 at 4:49 Comment(0)
F
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();
Follansbee answered 18/3, 2012 at 12:18 Comment(5)
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.DATATurkey
The The data stream for the file, hmm? Then the documentation is crappy.Follansbee
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.Turkey
Regarding DISPLAY_NAME and TITLE: The filename is only used as a default 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.Turkey
@Boris I have tried to use this code but doesn't work ...the extension string results nullNovanovaculite
T
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();
Turkey answered 18/3, 2012 at 12:14 Comment(0)
D
0

I think this should use MediaStore.MediaColumns.MIME_TYPE

String[] projection = { MediaStore.MediaColumns.DATA,
        MediaStore.MediaColumns.MIME_TYPE };
Dayton answered 17/5, 2013 at 9:40 Comment(0)
P
0

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

 String[] fileArr = picturePath.split("\\.");
    
 String fileExtension = fileArr[fileArr.length - 1];
Paranoiac answered 17/5, 2022 at 13:40 Comment(0)
B
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()
}
Beech answered 26/8, 2023 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.