0

While selecting image using the inbuilt CropImageActivity, the picker shows option to select files (of any type) from some external app (WPS Office for my case). So when I select a pdf file (say), onSetImageUriComplete() doesn't cause any error.

@Override
    public void onSetImageUriComplete(CropImageView cropImageView, Uri uri, Exception error) {
        progressView.setVisibility(View.INVISIBLE);
        if (error != null) {
            Log.e(LOG_TAG, "Failed to  load image for cropping", error);
            AndroidUtils.showToast("Unable to upload", this);
            finish();
        }
    }

Error is not null for such cases. So, nothing shows up in UI and I don't have any way to know if it is an image or not.

I tried checking the extension from URI but in some models (One Plus X for my case), uri doesn't necessarily contain an extension.

I also tried loading the uri into a File and then check using this code:

public static boolean isImage(File file) {
        if (file == null || !file.exists()) {
            return false;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getPath(), options);
        return options.outWidth != -1 && options.outHeight != -1;
    }

But, for One Plus X it again returns false. Is there any other way (which is not resource intensive) to check if the fetched file is an image or not?

Avinash Gupta
  • 389
  • 4
  • 16

1 Answers1

1

So, nothing shows up in UI and I don't have any way to know if it is an image or not.

Call getType() on a ContentResolver, passing in the Uri. If the MIME type starts with image/, it is an image.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491