简体   繁体   English

从从画廊或相机中挑选的图像中获取文件扩展名,作为字符串

[英]Get the file extension from images picked from gallery or camera, as string

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.我想获取从画廊加载或从相机中挑选的图像的图像扩展名(例如“jpg”、“png”、“bmp”ecc。)作为字符串。

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

或者

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

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.我知道这已经很晚了,但是对于那些当路径包含空格时 getContentResolver().getType(uri) 返回 null 时仍然存在问题的人。 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..).此方法返回文件的扩展名(jpg、png、pdf、epub 等)。

 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;
}
getContentResolver().getType(theReceivedUri);

上面的代码片段让你的类型为“媒体/格式”

you have multiple choice to get extension of file:like:您有多种选择来获取文件的扩展名:如:

1- String filename = uri.getLastPathSegment(); 1- String filename = uri.getLastPathSegment(); see this link看到这个链接

2- you can use this code also 2-您也可以使用此代码

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

but this not good aproch.但这不是很好的方法。

3-if you have URI of file then use this Code 3-如果您有文件的 URI,则使用此代码

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

4-if you have URL then use this code 4-如果您有 URL,则使用此代码

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

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.首先,我们将创建一个方法GetFileExtension ,我们要调用它来查找文件、图像、数据和文档的扩展名。 Here I took a variable named:这里我取了一个名为:

Uri videouri = data.getData();

in OnActivity Result then I invoke it in,OnActivity Result 然后我调用它,

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

Now make a Class to class GetFileExtension :现在为类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.由于这种方法,我们可以在 java 和 android 中找到任何文件的扩展名。 I'm 100 % sure it will work for you all who are making corporate App.我 100 % 确定它适用于所有制作企业应用程序的人。 If you like then vote for me..喜欢就投我一票吧。。

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

For "content://" sheme对于“content://”sheme

fun Uri.getFileExtension(context: Context): String? {
    return MimeTypeMap.getSingleton()
        .getExtensionFromMimeType(context.contentResolver.getType(this))
}

I think this should use MediaStore.MediaColumns.MIME_TYPE我认为这应该使用MediaStore.MediaColumns.MIME_TYPE

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

You can split string to strings array and get last index of it您可以将字符串拆分为字符串数组并获取它的最后一个索引

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

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 .如果你得到content://media Uris 作为结果并且你想要扩展,那么你必须像你一样查询数据库并从filePath中提取 if 。 Eg with this例如用这个

To get the filename out of a full path the simplest solution is要从完整路径中获取文件名,最简单的解决方案是

String filename = (new File(filePath)).getName();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM