Example usage for org.apache.commons.imaging.formats.tiff.constants ExifTagConstants EXIF_TAG_DATE_TIME_ORIGINAL

List of usage examples for org.apache.commons.imaging.formats.tiff.constants ExifTagConstants EXIF_TAG_DATE_TIME_ORIGINAL

Introduction

In this page you can find the example usage for org.apache.commons.imaging.formats.tiff.constants ExifTagConstants EXIF_TAG_DATE_TIME_ORIGINAL.

Prototype

TagInfoAscii EXIF_TAG_DATE_TIME_ORIGINAL

To view the source code for org.apache.commons.imaging.formats.tiff.constants ExifTagConstants EXIF_TAG_DATE_TIME_ORIGINAL.

Click Source Link

Usage

From source file:com.mycompany.jpegrenamer.MetaDataReader.java

public Map<String, String> getExifMetadata(final File jpegImageFile)
        throws ImageReadException, IOException, ImageWriteException {
    Map<String, String> res = new HashMap<>();
    Map<String, String> location = new HashMap();
    ;/*w  w  w. ja  va 2  s .co  m*/
    // note that metadata might be null if no metadata is found.
    final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
    boolean isClassOk = metadata instanceof JpegImageMetadata;
    if (!isClassOk || (null == metadata)) {
        return res;
    }
    final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
    if (jpegMetadata == null) {
        logger.info("File does not contain metadata - " + jpegImageFile.getCanonicalPath());
        return res;
    }
    String dateOfCaptureString = getTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME);
    SimpleDateFormat sdf = new SimpleDateFormat("''yyyy:MM:dd hh:mm:ss''");
    Date dateOfCapture = null;
    try {
        dateOfCapture = sdf.parse(dateOfCaptureString);
        final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss", Locale.ENGLISH);
        res.put("date", df.format(dateOfCapture));
    } catch (ParseException ex) {
        logger.error("", ex);
    }
    //        s = getTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME);
    printTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME);
    printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
    printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
    printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
    printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE);
    printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
    printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE);
    if (null != jpegMetadata) {
        // note that exif might be null if no Exif metadata is found.
        final TiffImageMetadata exif = jpegMetadata.getExif();
        //logger.info(jpegMetadata.toString());
        if (null != exif) {
            //logger.info(exif.toString());
            final TiffImageMetadata.GPSInfo gpsInfo = exif.getGPS();
            if (null != gpsInfo) {
                final String gpsDescription = gpsInfo.toString();
                final double longitude = gpsInfo.getLongitudeAsDegreesEast();
                final double latitude = gpsInfo.getLatitudeAsDegreesNorth();
                logger.info("    " + "GPS Description: " + gpsDescription);
                logger.info("    " + "GPS Longitude (Degrees East): " + longitude);
                logger.info("    " + "GPS Latitude (Degrees North): " + latitude);
                try {
                    Locale fmtLocale = Locale.US;
                    NumberFormat formatter = NumberFormat.getNumberInstance(fmtLocale);
                    formatter.setGroupingUsed(false);
                    location = getAddressByGpsCoordinates(formatter.format(latitude),
                            formatter.format(longitude));
                    if (location != null) {
                        res.putAll(location);
                    }
                } catch (MalformedURLException ex) {
                    logger.error("", ex);
                } catch (org.json.simple.parser.ParseException ex) {
                    logger.error("", ex);
                }
                logger.info("    " + location);
            }
            // more specific example of how to manually access GPS values
            final TiffField gpsLatitudeRefField = jpegMetadata
                    .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
            final TiffField gpsLatitudeField = jpegMetadata
                    .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE);
            final TiffField gpsLongitudeRefField = jpegMetadata
                    .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
            final TiffField gpsLongitudeField = jpegMetadata
                    .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE);
            if (gpsLatitudeRefField != null && gpsLatitudeField != null && gpsLongitudeRefField != null
                    && gpsLongitudeField != null) {
                // all of these values are strings.
                final String gpsLatitudeRef = (String) gpsLatitudeRefField.getValue();
                final RationalNumber[] gpsLatitude = (RationalNumber[]) (gpsLatitudeField.getValue());
                final String gpsLongitudeRef = (String) gpsLongitudeRefField.getValue();
                final RationalNumber[] gpsLongitude = (RationalNumber[]) gpsLongitudeField.getValue();
                final RationalNumber gpsLatitudeDegrees = gpsLatitude[0];
                final RationalNumber gpsLatitudeMinutes = gpsLatitude[1];
                final RationalNumber gpsLatitudeSeconds = gpsLatitude[2];
                final RationalNumber gpsLongitudeDegrees = gpsLongitude[0];
                final RationalNumber gpsLongitudeMinutes = gpsLongitude[1];
                final RationalNumber gpsLongitudeSeconds = gpsLongitude[2];
                // This will format the gps info like so:
                //
                // gpsLatitude: 8 degrees, 40 minutes, 42.2 seconds S
                // gpsLongitude: 115 degrees, 26 minutes, 21.8 seconds E
                logger.info("    " + "GPS Latitude: " + gpsLatitudeDegrees.toDisplayString() + " degrees, "
                        + gpsLatitudeMinutes.toDisplayString() + " minutes, "
                        + gpsLatitudeSeconds.toDisplayString() + " seconds " + gpsLatitudeRef);
                logger.info("    " + "GPS Longitude: " + gpsLongitudeDegrees.toDisplayString() + " degrees, "
                        + gpsLongitudeMinutes.toDisplayString() + " minutes, "
                        + gpsLongitudeSeconds.toDisplayString() + " seconds " + gpsLongitudeRef);
            }
            logger.info("");
            final List<ImageMetadata.ImageMetadataItem> items = jpegMetadata.getItems();
            for (int i = 0; i < items.size(); i++) {
                final ImageMetadata.ImageMetadataItem item = items.get(i);
                // logger.info("    " + "item: " + item);
            }
            logger.info("");
        }
    }
    return res;
}

From source file:com.cons.gps2exif.exif.ReadMetaData.java

public Date getPhotographyDate(final File file) throws ImageReadException, IOException {
    // get all metadata stored in EXIF format (ie. from JPEG or TIFF).
    final ImageMetadata metadata = Imaging.getMetadata(file);

    String rtnValue = "";

    if (metadata instanceof JpegImageMetadata) {
        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

        // print out various interesting EXIF tags.
        rtnValue = getTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);

        if (null == rtnValue || rtnValue.isEmpty()) {
            rtnValue = getTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
        }/*  ww w  .j av  a  2 s . c o  m*/

        if (null == rtnValue || rtnValue.isEmpty()) {
            rtnValue = getTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME);
        }

        if (null == rtnValue || rtnValue.isEmpty()) {
            return null;
        }

    }
    rtnValue = rtnValue.replace("'", "");

    return getDateFromTiffDateStr(rtnValue);
}

From source file:net.mozq.picto.core.ProcessCore.java

private static ProcessDataStatus process(ProcessCondition processCondition, ProcessData processData,
        Function<ProcessData, ProcessDataStatus> overwriteConfirm) throws IOException {

    ProcessDataStatus status;/*ww  w .  j  a  v a 2 s .  co  m*/

    Path destParentPath = processData.getDestPath().getParent();
    if (destParentPath != null) {
        Files.createDirectories(destParentPath);
    }

    if (processCondition.isCheckDigest()
            || (processCondition.isChangeExifDate() && processData.getBaseDate() != null)
            || processCondition.isRemveExifTagsGps() || processCondition.isRemveExifTagsAll()) {
        Path destTempPath = null;
        try {
            destTempPath = Files.createTempFile(processData.getDestPath().getParent(),
                    processData.getDestPath().getFileName().toString(), null);

            if (processCondition.isCheckDigest()) {
                String algorithm = FILE_DIGEST_ALGORITHM;

                MessageDigest srcMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(processData.getSrcPath())), srcMD)) {
                    Files.copy(is, destTempPath, OPTIONS_COPY_REPLACE);
                }
                byte[] srcDigest = srcMD.digest();

                MessageDigest destMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(destTempPath)), destMD)) {
                    byte[] b = new byte[1024];
                    while (is.read(b) != -1) {
                    }
                }
                byte[] destDigest = destMD.digest();

                if (!isSame(srcDigest, destDigest)) {
                    throw new PictoFileDigestMismatchException(
                            Messages.getString("message.error.digest.mismatch"));
                }
            } else if (processCondition.isRemveExifTagsAll()) {
                ExifRewriter exifRewriter = new ExifRewriter();
                try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                    exifRewriter.removeExifMetadata(processData.getSrcPath().toFile(), os);
                } catch (ImageReadException | ImageWriteException e) {
                    throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                }
            } else if (processCondition.isChangeExifDate() || processCondition.isRemveExifTagsGps()) {
                ImageMetadata imageMetadata = getImageMetadata(processData.getSrcPath());
                TiffOutputSet outputSet = getOutputSet(imageMetadata);
                if (outputSet == null) {
                    Files.copy(processData.getSrcPath(), destTempPath, OPTIONS_COPY_REPLACE);
                } else {
                    if (processCondition.isChangeExifDate()) {
                        SimpleDateFormat exifDateFormat = new SimpleDateFormat(EXIF_DATE_PATTERN);
                        exifDateFormat.setTimeZone(processCondition.getTimeZone());
                        String exifBaseDate = exifDateFormat.format(processData.getBaseDate());

                        DecimalFormat exifSubsecFormat = new DecimalFormat(EXIF_SUBSEC_PATTERN);
                        String exifBaseSubsec = exifSubsecFormat
                                .format((int) (processData.getBaseDate().getTime() / 10) % 100);

                        try {
                            TiffOutputDirectory rootDirectory = outputSet.getRootDirectory();
                            TiffOutputDirectory exifDirectory = outputSet.getExifDirectory();
                            if (rootDirectory != null) {
                                rootDirectory.removeField(TiffTagConstants.TIFF_TAG_DATE_TIME);
                                rootDirectory.add(TiffTagConstants.TIFF_TAG_DATE_TIME, exifBaseDate);
                            }
                            if (exifDirectory != null) {
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME, exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL,
                                        exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED,
                                        exifBaseSubsec);
                            }
                        } catch (ImageWriteException e) {
                            throw new PictoFileChangeException(Messages.getString("message.error.edit.file"),
                                    e);
                        }
                    }

                    if (processCondition.isRemveExifTagsGps()) {
                        outputSet.removeField(ExifTagConstants.EXIF_TAG_GPSINFO);
                    }

                    ExifRewriter exifRewriter = new ExifRewriter();
                    try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                        exifRewriter.updateExifMetadataLossless(processData.getSrcPath().toFile(), os,
                                outputSet);
                    } catch (ImageReadException | ImageWriteException e) {
                        throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                    }
                }
            }

            Path destPath;
            if (processCondition.getOperationType() == OperationType.Overwrite) {
                destPath = processData.getSrcPath();
            } else {
                destPath = processData.getDestPath();
            }
            try {
                Files.move(destTempPath, destPath, OPTIONS_MOVE);
                if (processCondition.getOperationType() == OperationType.Move) {
                    Files.deleteIfExists(processData.getSrcPath());
                }
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    // Overwrite
                    Files.move(destTempPath, destPath, OPTIONS_MOVE_REPLACE);
                    if (processCondition.getOperationType() == OperationType.Move) {
                        Files.deleteIfExists(processData.getSrcPath());
                    }
                    status = ProcessDataStatus.Success;
                }
            }
        } finally {
            if (destTempPath != null) {
                Files.deleteIfExists(destTempPath);
            }
        }
    } else {
        switch (processCondition.getOperationType()) {
        case Copy:
            try {
                Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Move:
            try {
                Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Overwrite:
            // NOP
            status = ProcessDataStatus.Success;
            break;
        default:
            throw new IllegalStateException(processCondition.getOperationType().toString());
        }
    }

    if (status == ProcessDataStatus.Success) {
        FileTime creationFileTime = processData.getSrcFileAttributes().creationTime();
        FileTime modifiedFileTime = processData.getSrcFileAttributes().lastModifiedTime();
        FileTime accessFileTime = processData.getSrcFileAttributes().lastAccessTime();
        if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate()
                || processCondition.isChangeFileAccessDate()) {
            if (processData.getBaseDate() != null) {
                FileTime baseFileTime = FileTime.fromMillis(processData.getBaseDate().getTime());
                if (processCondition.isChangeFileCreationDate()) {
                    creationFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileModifiedDate()) {
                    modifiedFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileAccessDate()) {
                    accessFileTime = baseFileTime;
                }
            }
        }
        BasicFileAttributeView attributeView = Files.getFileAttributeView(processData.getDestPath(),
                BasicFileAttributeView.class);
        attributeView.setTimes(modifiedFileTime, accessFileTime, creationFileTime);
    }

    return status;
}

From source file:net.mozq.picto.core.ProcessCore.java

private static Date getExifDate(ImageMetadata imageMetadata) throws IOException {
    Date photoTakenDate = getEXIFDateValue(imageMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL,
            ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL);
    if (photoTakenDate == null) {
        photoTakenDate = getEXIFDateValue(imageMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED,
                ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED);
        if (photoTakenDate == null) {
            photoTakenDate = getEXIFDateValue(imageMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME,
                    ExifTagConstants.EXIF_TAG_SUB_SEC_TIME);
        }//from  ww  w . j  ava  2 s .  co  m
    }

    return photoTakenDate;
}

From source file:net.tourbook.photo.Photo.java

/**
 * Date/Time/* w w w  .j a  va2  s .c o  m*/
 * 
 * @param jpegMetadata
 * @param file
 * @return
 */
private LocalDateTime getExifValueDate(final JpegImageMetadata jpegMetadata) {

    //      /*
    //       * !!! time is not correct, maybe it is the time when the GPS signal was
    //       * received !!!
    //       */
    //      printTagValue(jpegMetadata, TiffConstants.GPS_TAG_GPS_TIME_STAMP);

    try {

        final TiffField exifDate = jpegMetadata.findEXIFValueWithExactMatch(//
                ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);

        if (exifDate != null) {
            return LocalDateTime.parse(exifDate.getStringValue(), _dtParser);
        }

        final TiffField tiffDate = jpegMetadata
                .findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_DATE_TIME);

        if (tiffDate != null) {
            return LocalDateTime.parse(tiffDate.getStringValue(), _dtParser);
        }

    } catch (final Exception e) {
        // ignore
    }

    return null;
}

From source file:net.tourbook.photo.Photo.java

private LocalDateTime getTiffValueDate(final TiffImageMetadata tiffMetadata) {

    try {/* w w w  .j av a  2  s  .c  o m*/

        final TiffField exifDate = tiffMetadata.findField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, true);

        if (exifDate != null) {
            return LocalDateTime.parse(exifDate.getStringValue(), _dtParser);
        }

        final TiffField date = tiffMetadata.findField(TiffTagConstants.TIFF_TAG_DATE_TIME, true);
        if (date != null) {
            return LocalDateTime.parse(date.getStringValue(), _dtParser);
        }

    } catch (final Exception e) {
        // ignore
    }

    return null;
}

From source file:org.apache.commons.imaging.examples.MetadataExample.java

public static void metadataExample(final File file) throws ImageReadException, IOException {
    // get all metadata stored in EXIF format (ie. from JPEG or TIFF).
    final ImageMetadata metadata = Imaging.getMetadata(file);

    // System.out.println(metadata);

    if (metadata instanceof JpegImageMetadata) {
        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

        // Jpeg EXIF metadata is stored in a TIFF-based directory structure
        // and is identified with TIFF tags.
        // Here we look for the "x resolution" tag, but
        // we could just as easily search for any other tag.
        ///*  ww w  .j  ava2  s . co  m*/
        // see the TiffConstants file for a list of TIFF tags.

        System.out.println("file: " + file.getPath());

        // print out various interesting EXIF tags.
        printTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_XRESOLUTION);
        printTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME);
        printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
        printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
        printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_ISO);
        printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE);
        printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
        printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE);
        printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
        printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE);
        printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
        printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE);

        System.out.println();

        // simple interface to GPS data
        final TiffImageMetadata exifMetadata = jpegMetadata.getExif();
        if (null != exifMetadata) {
            final TiffImageMetadata.GPSInfo gpsInfo = exifMetadata.getGPS();
            if (null != gpsInfo) {
                final String gpsDescription = gpsInfo.toString();
                final double longitude = gpsInfo.getLongitudeAsDegreesEast();
                final double latitude = gpsInfo.getLatitudeAsDegreesNorth();

                System.out.println("    " + "GPS Description: " + gpsDescription);
                System.out.println("    " + "GPS Longitude (Degrees East): " + longitude);
                System.out.println("    " + "GPS Latitude (Degrees North): " + latitude);
            }
        }

        // more specific example of how to manually access GPS values
        final TiffField gpsLatitudeRefField = jpegMetadata
                .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
        final TiffField gpsLatitudeField = jpegMetadata
                .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE);
        final TiffField gpsLongitudeRefField = jpegMetadata
                .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
        final TiffField gpsLongitudeField = jpegMetadata
                .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE);
        if (gpsLatitudeRefField != null && gpsLatitudeField != null && gpsLongitudeRefField != null
                && gpsLongitudeField != null) {
            // all of these values are strings.
            final String gpsLatitudeRef = (String) gpsLatitudeRefField.getValue();
            final RationalNumber gpsLatitude[] = (RationalNumber[]) (gpsLatitudeField.getValue());
            final String gpsLongitudeRef = (String) gpsLongitudeRefField.getValue();
            final RationalNumber gpsLongitude[] = (RationalNumber[]) gpsLongitudeField.getValue();

            final RationalNumber gpsLatitudeDegrees = gpsLatitude[0];
            final RationalNumber gpsLatitudeMinutes = gpsLatitude[1];
            final RationalNumber gpsLatitudeSeconds = gpsLatitude[2];

            final RationalNumber gpsLongitudeDegrees = gpsLongitude[0];
            final RationalNumber gpsLongitudeMinutes = gpsLongitude[1];
            final RationalNumber gpsLongitudeSeconds = gpsLongitude[2];

            // This will format the gps info like so:
            //
            // gpsLatitude: 8 degrees, 40 minutes, 42.2 seconds S
            // gpsLongitude: 115 degrees, 26 minutes, 21.8 seconds E

            System.out.println("    " + "GPS Latitude: " + gpsLatitudeDegrees.toDisplayString() + " degrees, "
                    + gpsLatitudeMinutes.toDisplayString() + " minutes, " + gpsLatitudeSeconds.toDisplayString()
                    + " seconds " + gpsLatitudeRef);
            System.out.println("    " + "GPS Longitude: " + gpsLongitudeDegrees.toDisplayString() + " degrees, "
                    + gpsLongitudeMinutes.toDisplayString() + " minutes, "
                    + gpsLongitudeSeconds.toDisplayString() + " seconds " + gpsLongitudeRef);

        }

        System.out.println();

        final List<ImageMetadataItem> items = jpegMetadata.getItems();
        for (int i = 0; i < items.size(); i++) {
            final ImageMetadataItem item = items.get(i);
            System.out.println("    " + "item: " + item);
        }

        System.out.println();
    }
}

From source file:org.openstreetmap.josm.plugins.mapillary.io.export.MapillaryExportWriterThread.java

@Override
public void run() {
    this.monitor.setCustomText("Downloaded 0/" + this.amount);
    BufferedImage img;//from ww  w  . ja  v a  2  s .  c om
    MapillaryAbstractImage mimg;
    String finalPath = "";
    for (int i = 0; i < this.amount; i++) {
        try {
            img = this.queue.take();
            mimg = this.queueImages.take();
            if (img == null || mimg == null)
                throw new IllegalStateException("Null image");
            if (this.path == null && mimg instanceof MapillaryImportedImage) {
                String path = ((MapillaryImportedImage) mimg).getFile().getPath();
                finalPath = path.substring(0, path.lastIndexOf('.'));
            } else if (mimg instanceof MapillaryImage) {
                finalPath = this.path + '/' + ((MapillaryImage) mimg).getKey();
            } else if (mimg instanceof MapillaryImportedImage) {
                finalPath = this.path + '/' + ((MapillaryImportedImage) mimg).getFile().getName();
            }

            // Transforms the image into a byte array.
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(img, "jpg", outputStream);
            byte[] imageBytes = outputStream.toByteArray();

            // Write EXIF tags
            TiffOutputSet outputSet = null;
            TiffOutputDirectory exifDirectory;
            TiffOutputDirectory gpsDirectory;
            // If the image is imported, loads the rest of the EXIF data.
            if (mimg instanceof MapillaryImportedImage) {
                final ImageMetadata metadata = Imaging.getMetadata(((MapillaryImportedImage) mimg).getFile());
                final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
                if (null != jpegMetadata) {
                    final TiffImageMetadata exif = jpegMetadata.getExif();
                    if (null != exif) {
                        outputSet = exif.getOutputSet();
                    }
                }
            }
            if (null == outputSet) {
                outputSet = new TiffOutputSet();
            }
            exifDirectory = outputSet.getOrCreateExifDirectory();
            gpsDirectory = outputSet.getOrCreateGPSDirectory();

            gpsDirectory.removeField(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION_REF);
            gpsDirectory.add(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION_REF,
                    GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION_REF_VALUE_TRUE_NORTH);

            gpsDirectory.removeField(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION);
            gpsDirectory.add(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION,
                    RationalNumber.valueOf(mimg.getMovingCa()));

            exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
            if (mimg instanceof MapillaryImportedImage) {
                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL,
                        mimg.getDate("yyyy/MM/dd HH:mm:ss"));
            } else if (mimg instanceof MapillaryImage) {
                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL,
                        mimg.getDate("yyyy/MM/dd HH/mm/ss"));
            }
            outputSet.setGPSInDegrees(mimg.getMovingLatLon().lon(), mimg.getMovingLatLon().lat());
            OutputStream os = new BufferedOutputStream(new FileOutputStream(finalPath + ".jpg"));
            new ExifRewriter().updateExifMetadataLossless(imageBytes, os, outputSet);

            os.close();
        } catch (InterruptedException e) {
            Main.info("Mapillary export cancelled");
            return;
        } catch (IOException | ImageReadException | ImageWriteException e) {
            Main.error(e);
        }

        // Increases the progress bar.
        this.monitor.worked(PleaseWaitProgressMonitor.PROGRESS_BAR_MAX / this.amount);
        this.monitor.setCustomText("Downloaded " + (i + 1) + "/" + this.amount);
    }
}

From source file:org.openstreetmap.josm.plugins.mapillary.oauth.UploadTest.java

/**
 * Tests the {@link UploadUtils#updateFile(MapillaryImportedImage)} method.
 *//*w  w w  .  j a v  a 2s .co  m*/
@Test
public void updateFileTest() throws IOException {
    File image = new File("images/icon16.png");
    MapillaryImportedImage img = ImageUtil.readImagesFrom(image, new LatLon(0, 0)).get(0);
    File updatedFile = null;
    try {
        updatedFile = UploadUtils.updateFile(img);
        ImageMetadata metadata = Imaging.getMetadata(updatedFile);
        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
        assertTrue(jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF) != null);
        assertTrue(jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE) != null);
        assertTrue(jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF) != null);
        assertTrue(jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE) != null);
        assertTrue(jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION) != null);
        assertTrue(
                jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL) != null);
        assertEquals(0,
                MapillaryUtils.degMinSecToDouble(
                        (RationalNumber[]) jpegMetadata
                                .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE).getValue(),
                        jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF)
                                .getValue().toString()),
                0.01);
        assertEquals(0,
                MapillaryUtils.degMinSecToDouble(
                        (RationalNumber[]) jpegMetadata
                                .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE).getValue(),
                        jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF)
                                .getValue().toString()),
                0.01);

    } catch (ImageReadException | ImageWriteException | IOException e) {
        fail();
    } finally {
        updatedFile.delete();
    }
}

From source file:org.openstreetmap.josm.plugins.mapillary.oauth.UploadUtils.java

/**
 * Returns a file containing the picture and an updated version of the EXIF
 * tags.//from ww  w  .j av  a  2s  .  c  o  m
 *
 * @param image The image to be uploaded
 * @return A File object containing the picture and an updated version of the
 * EXIF tags.
 * @throws ImageReadException  if there are errors reading the image from the file.
 * @throws IOException         if there are errors getting the metadata from the file or writing
 *                             the output.
 * @throws ImageWriteException if there are errors writing the image in the file.
 */
static File updateFile(MapillaryImportedImage image)
        throws ImageReadException, IOException, ImageWriteException {
    TiffOutputSet outputSet = null;
    TiffOutputDirectory exifDirectory;
    TiffOutputDirectory gpsDirectory;
    TiffOutputDirectory rootDirectory;

    // If the image is imported, loads the rest of the EXIF data.
    JpegImageMetadata jpegMetadata = null;
    try {
        ImageMetadata metadata = Imaging.getMetadata(image.getFile());
        jpegMetadata = (JpegImageMetadata) metadata;
    } catch (Exception e) {
        Main.warn(e);
    }

    if (null != jpegMetadata) {
        final TiffImageMetadata exif = jpegMetadata.getExif();
        if (null != exif) {
            outputSet = exif.getOutputSet();
        }
    }
    if (null == outputSet) {
        outputSet = new TiffOutputSet();
    }
    gpsDirectory = outputSet.getOrCreateGPSDirectory();
    exifDirectory = outputSet.getOrCreateExifDirectory();
    rootDirectory = outputSet.getOrCreateRootDirectory();

    gpsDirectory.removeField(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION_REF);
    gpsDirectory.add(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION_REF,
            GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION_REF_VALUE_TRUE_NORTH);

    gpsDirectory.removeField(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION);
    gpsDirectory.add(GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION, RationalNumber.valueOf(image.getMovingCa()));

    exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
    exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, image.getDate("yyyy/MM/dd HH:mm:ss"));

    // Removes the ImageDescription tag, that causes problems in the upload.
    rootDirectory.removeField(TiffTagConstants.TIFF_TAG_IMAGE_DESCRIPTION);

    outputSet.setGPSInDegrees(image.getMovingLatLon().lon(), image.getMovingLatLon().lat());
    File tempFile = File.createTempFile("imagetoupload_" + c, ".tmp");
    c++;
    OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));

    // Transforms the image into a byte array.
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageIO.write(image.getImage(), "jpg", outputStream);
    byte[] imageBytes = outputStream.toByteArray();
    new ExifRewriter().updateExifMetadataLossless(imageBytes, os, outputSet);
    os.close();
    return tempFile;
}