Richard Nichols Richard Nichols - 1 month ago 11
iOS Question

Phonegap / Cordova camera plugin - how to get photo's date/time stamp?

I have a Phonegap app that needs to let the user both take photos using the phone's camera and let the user select from photo's already on the device.

I need to capture the date/time the photo was taken as part of the metadata, but I'm having a hard time figuring out how to do this with Phonegap / Cordova.

Initially I thought I could use the File API's FileEntry.getMetadata() call but this doesn't return a valid date for the modificationTime attribute. I think that phonegap also transforms the file on the device so that the you recieve back from the camera plugin is not the original file on the device, so even if the getMetadata() call worked, the date wouldn't be the correct one.

Is there any other way around this, short of writing my own version of the camera plugin for each platform I need?

Seems crazy that this would be the only way around it.

Answer

So, I've managed to figure this out.

The date/time stamp along with a bunch of other information can be retrieved from the EXIF data tags inside the JPEG file. This can be done using this helpful JS library - https://github.com/jseidelin/exif-js

Unfortunately the Cordova camera plugin for Android doesn't copy EXIF tags when transforming an image selected from the gallery, only when taking an image using the camera, so this is a problem, but I will fix this by forking the plugin. The iOS version of the plugin seems to do this right thing.

Code for anyone interested -

var source = fromCamera 
       ? Camera.PictureSourceType.CAMERA 
       : Camera.PictureSourceType.PHOTOLIBRARY;

var opts = {
    encodingType: Camera.EncodingType.JPEG,
    sourceType: source,
    destinationType: Camera.DestinationType.NATIVE_URI
};

navigator.camera.getPicture(
        function(imageURI) {
            window.resolveLocalFileSystemURL(imageURI,
                    function(entry) {
                        entry.file(function(file) {
                            EXIF.getData(file, function() {
                                var datetime = EXIF.getTag(this, "DateTimeOriginal");
                                alert(datetime);
                            });                                                

                            // do something useful....

                        }, standardErrorHandler);
                    },
                    function(e) {
                        alert('Unexpected error obtaining image file.');
                        standardErrorHandler(e);
                    });
        },
        function() {
            // nada - cancelled
        },
        opts);