4

I want to get Exif data for an image that I pick from Android gallery or similar apps like Google Photos. Here are the methods that I am using for getting image file from Uri:

public static String getActualPathFromUri(@NonNull Context context, @NonNull Uri selectedImageUri) {
        Bitmap bitmap = null;
        try {
            bitmap = getBitmapFromUri(context, selectedImageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bitmap == null) {
            return null;
        }

        File imageFileFolder = new File(context.getCacheDir(), "example");
        if (!imageFileFolder.exists()) {
            imageFileFolder.mkdir();
        }

        FileOutputStream out = null;

        File imageFileName = new File(imageFileFolder, "example-" + System.currentTimeMillis() + ".jpg");
        try {
            out = new FileOutputStream(imageFileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (IOException e) {

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imageFileName.getAbsolutePath();
    }

    private static Bitmap getBitmapFromUri(@NonNull Context context, @NonNull Uri uri) throws IOException {

        ParcelFileDescriptor parcelFileDescriptor =
                context.getContentResolver().openFileDescriptor(uri, "r");
        assert parcelFileDescriptor != null;
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
}

The reason I am opting for Bitmap from the Uri instead of getting system filename is because the method is fragmented for different versions of Android. Plus, in apps like Google Photos, some photos are shown directly from server and are not stored on the device, so getting filename is not possible. Even if I get the filename, I get Security Exception when trying to use that in my app.

The problem with this approach is, when I get the Bitmap, I don't get the Exif data. But I need the Exif data and attach it to the file that I save in my cache folder so that when I upload the image to server, it gets the image along with Exif so that it can do some further processing. The reason, I need to save it as a file or at least get the file, if it already exists in the system is because Retrofit needs a File object which then gets converted to TypedFile and sent to server using Multipart request.

So, how can I accurately get the Exif information from any kind of image Uri(local or on server) and then save the image along with it's Exif data so that I can send it to the server.

Amit Tiwari
  • 3,684
  • 6
  • 33
  • 75

0 Answers0