Capturing/Selecting images and returning its type

2019-09-10 18:28发布

问题:

How can I allow the user to choose between capturing an image or selecting it from the gallery, and I want to know the type of the photo afterwards (PNG/JPG). I'm using this code but it is not working well.

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                mImg.setImageBitmap(photo);
            } else if (requestCode == SELECT_FILE) {
                Uri selectedImageUri = data.getData();
                String[] projection = {MediaStore.MediaColumns.DATA};
                CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri, projection, null, null,
                        null);
                Cursor cursor = cursorLoader.loadInBackground();
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();

                String selectedImagePath = cursor.getString(column_index);

                Bitmap bm;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(selectedImagePath, options);
                final int REQUIRED_SIZE = 200;
                int scale = 1;
                while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                        && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
                options.inSampleSize = scale;
                options.inJustDecodeBounds = false;
                bm = BitmapFactory.decodeFile(selectedImagePath, options);

                mImg.setImageBitmap(bm);
                mImg.setAlpha(1);

            }
}
}

回答1:

I want to know the type of the photo afterwards (PNG/JPG)

Call getType() on a ContentResolver, passing in the Uri.

I'm using this code but it is not working well.

Delete most of what you have, as your selectedImagePath code will fail on most Android devices and you are decoding the bitmap on the main application thread. Use an image-loading library like Picasso to handle the image loading for you, asynchronous, including the scaling. Picasso can use the Uri directly without any of the flawed selectedImagePath stuff. Then, all you need is the getType() call to get the MIME type of the image. Your entire requestCode == SELECT_FILE block will be replaced by 2-3 lines of code.



回答2:

You have to install Apache Commons Io Use FilenameUtils.getExtention() from this lib

String ext = FilenameUtils.getExtension("/path/to/file/foo.txt");

i think this will help you