Search code examples
androidimagefilechooser

Cannot set a fileIntent for image files of type jpg, png and jpeg


I'm using the following code:

Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileIntent.setType("image/jpg|image/png|image/jpeg"); 
startActivityForResult(fileIntent, REQUEST_FILE);

I believe that code should allow me to select any jpg, png or jpeg file, but it doesn't.

On the other hand changing fileIntent.setType("image/jpg|image/png|image/jpeg"); to fileIntent.setType("image/*"); allows to select the file. But it also allows to select another image files I don't want to.

What needs to be corrected in fileIntent.setType("image/jpg|image/png|image/jpeg"); so it allows to choose files of those types and not other ones?


Solution

  • You can only specify a single mimetype with setType(), instead apply an extra with the key Intent.EXTRA_MIME_TYPES with an array of mimetypes:

    fileIntent.putExtra(Intent.EXTRA_MIME_TYPES, Arrays.asList("image/png", "image/jpeg").toArray());
    

    I have found that even when providing a list of mimetypes you may still need to apply intent.fileType("*/*"); to the intent regardless, however, the list of mimetypes will take preference.