Home » Android » android – Get the file extension from images picked from gallery or camera, as string

android – Get the file extension from images picked from gallery or camera, as string

Posted by: admin April 23, 2020 Leave a comment

Questions:

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;
    }
}
How to&Answers:
 filePath.substring(filePath.lastIndexOf(".")); // Extension with dot .jpg, .png

or

 filePath.substring(filePath.lastIndexOf(".") + 1); // Without dot jpg, png

Answer:

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

Answer:

getContentResolver().getType(theReceivedUri);

The above snippet gets you the type as “media/format”

Answer:

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

Answer:

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();

Answer:

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..

Answer:

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();

Answer:

I think this should use MediaStore.MediaColumns.MIME_TYPE

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