Example usage for org.apache.commons.imaging.formats.jpeg JpegImageMetadata getExif

List of usage examples for org.apache.commons.imaging.formats.jpeg JpegImageMetadata getExif

Introduction

In this page you can find the example usage for org.apache.commons.imaging.formats.jpeg JpegImageMetadata getExif.

Prototype

public TiffImageMetadata getExif() 

Source Link

Usage

From source file:MetadataExample.java

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

    if (metadata instanceof JpegImageMetadata) {
        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.
        ////from  w  ww  .j  a  v  a  2  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_DATE_TIME);
            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);
            printTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_ORIENTATION);
        }
        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);

        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<IImageMetadataItem> items = jpegMetadata.getItems();
        for (int i = 0; i < items.size(); i++) {
            final TiffImageMetadata.Item item = (Item) items.get(i);
            System.out.println("    " + "item: " + item + "::" + item.getClass());
        }

        System.out.println();
    }
}

From source file:adams.flow.transformer.exiftagoperation.ApacheCommonsExifTagRemove.java

/**
 * Processes the incoming data./*from   w  w w  .j  av  a  2  s.  c  o  m*/
 *
 * @param input   the input to process
 * @param errors   for storing errors
 * @return      the generated output
 */
@Override
protected Object doProcess(Object input, MessageCollection errors) {
    Object result;
    File inputFile;
    File tmpFile;
    JpegImageMetadata meta;
    TiffImageMetadata exif;
    TiffOutputSet outputSet;
    TiffOutputDirectory exifDir;
    FileOutputStream fos;
    BufferedOutputStream bos;

    result = null;

    if (input instanceof String)
        inputFile = new PlaceholderFile((String) input).getAbsoluteFile();
    else
        inputFile = ((File) input).getAbsoluteFile();
    tmpFile = TempUtils.createTempFile(getClass().getSimpleName().toLowerCase() + "-", ".jpg");

    fos = null;
    bos = null;
    try {
        meta = (JpegImageMetadata) Imaging.getMetadata(inputFile);
        if (meta != null) {
            exif = meta.getExif();
            if (exif != null) {
                outputSet = exif.getOutputSet();
                if (outputSet != null) {
                    exifDir = outputSet.getOrCreateExifDirectory();
                    if (exifDir != null) {
                        exifDir.removeField(m_Tag.getTagInfo());
                        fos = new FileOutputStream(tmpFile);
                        bos = new BufferedOutputStream(fos);
                        new ExifRewriter().updateExifMetadataLossless(inputFile, bos, outputSet);
                        if (!FileUtils.copy(tmpFile, inputFile))
                            errors.add("Failed to replace " + inputFile + " with updated EXIF from " + tmpFile);
                        if (!FileUtils.delete(tmpFile))
                            errors.add("Failed to delete tmp file: " + tmpFile);
                    } else {
                        errors.add("Failed to obtain EXIF directory: " + input);
                    }
                } else {
                    errors.add("Failed to obtain output set: " + input);
                }
            } else {
                errors.add("No EXIF meta-data available: " + input);
            }
        } else {
            errors.add("No meta-data available: " + input);
        }
    } catch (Exception e) {
        errors.add("Failed to read EXIF tag " + m_Tag + " from: " + input, e);
    } finally {
        FileUtils.closeQuietly(bos);
        FileUtils.closeQuietly(fos);
    }

    if (errors.isEmpty())
        result = input;

    return result;
}

From source file:adams.flow.transformer.exiftagoperation.ApacheCommonsExifTagWrite.java

/**
 * Processes the incoming data./*from  w  ww.  java  2s . c  o  m*/
 *
 * @param input   the input to process
 * @param errors   for storing errors
 * @return      the generated output
 */
@Override
protected Object doProcess(Object input, MessageCollection errors) {
    Object result;
    File inputFile;
    File tmpFile;
    JpegImageMetadata meta;
    TiffImageMetadata exif;
    TiffOutputSet outputSet;
    TiffOutputDirectory exifDir;
    FileOutputStream fos;
    BufferedOutputStream bos;

    result = null;

    if (input instanceof String)
        inputFile = new PlaceholderFile((String) input).getAbsoluteFile();
    else
        inputFile = ((File) input).getAbsoluteFile();
    tmpFile = TempUtils.createTempFile(getClass().getSimpleName().toLowerCase() + "-", ".jpg");

    fos = null;
    bos = null;
    try {
        meta = (JpegImageMetadata) Imaging.getMetadata(inputFile);
        if (meta != null) {
            exif = meta.getExif();
            if (exif != null) {
                outputSet = exif.getOutputSet();
                if (outputSet != null) {
                    exifDir = outputSet.getOrCreateExifDirectory();
                    if (exifDir != null) {
                        exifDir.removeField(m_Tag.getTagInfo());
                        if (m_Tag.getTagInfo() instanceof TagInfoAscii)
                            exifDir.add((TagInfoAscii) m_Tag.getTagInfo(), m_Value);
                        else if (m_Tag.getTagInfo() instanceof TagInfoByte)
                            exifDir.add((TagInfoByte) m_Tag.getTagInfo(), Byte.parseByte(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoShort)
                            exifDir.add((TagInfoShort) m_Tag.getTagInfo(), Short.parseShort(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoDouble)
                            exifDir.add((TagInfoDouble) m_Tag.getTagInfo(), Double.parseDouble(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoFloat)
                            exifDir.add((TagInfoFloat) m_Tag.getTagInfo(), Float.parseFloat(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoRational)
                            exifDir.add((TagInfoRational) m_Tag.getTagInfo(),
                                    RationalNumber.valueOf(Double.parseDouble(m_Value)));
                        else
                            errors.add("Unhandled tag info type: " + Utils.classToString(m_Tag.getTagInfo()));
                        if (errors.isEmpty()) {
                            fos = new FileOutputStream(tmpFile);
                            bos = new BufferedOutputStream(fos);
                            new ExifRewriter().updateExifMetadataLossless(inputFile, bos, outputSet);
                            if (!FileUtils.copy(tmpFile, inputFile))
                                errors.add("Failed to replace " + inputFile + " with updated EXIF from "
                                        + tmpFile);
                            if (!FileUtils.delete(tmpFile))
                                errors.add("Failed to delete tmp file: " + tmpFile);
                        }
                    } else {
                        errors.add("Failed to obtain EXIF directory: " + input);
                    }
                } else {
                    errors.add("Failed to obtain output set: " + input);
                }
            } else {
                errors.add("No EXIF meta-data available: " + input);
            }
        } else {
            errors.add("No meta-data available: " + input);
        }
    } catch (Exception e) {
        errors.add("Failed to read EXIF tag " + m_Tag + " from: " + input, e);
    } finally {
        FileUtils.closeQuietly(bos);
        FileUtils.closeQuietly(fos);
    }

    if (errors.isEmpty())
        result = input;

    return result;
}

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();
    ;//from w ww  .  j  av  a 2s  . c  o 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 void showAllMetaData(final File file) throws ImageReadException, IOException {
    // get all metadata stored in EXIF format (ie. from JPEG or TIFF).
    final ImageMetadata metadata = Imaging.getMetadata(file);

    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.
        ///*from   w  w  w  .ja v  a2  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.
        showTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_XRESOLUTION);
        showTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME);
        showTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
        showTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
        showTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_ISO);
        showTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE);
        showTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
        showTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE);
        showTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
        showTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE);
        showTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
        showTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE);
        showTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
        showTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE);

        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:name.hampton.mike.gallery.MetadataExtractor.java

public Map<String, Object> extractImageMetaData(final InputStream inputStream, Map<String, Object> metadataH)
        throws ImageReadException, IOException {
    // get all metadata stored in EXIF format (ie. from JPEG or TIFF).
    final ImageMetadata metadata = Imaging.getMetadata(inputStream, null);

    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.
        ///* w w w .ja v  a 2  s.  c  om*/
        // see the TiffConstants file for a list of TIFF tags.

        // out.println("file: " + file.getPath());
        JpegPhotoshopMetadata photoshopmetadata = jpegMetadata.getPhotoshop();
        metadataH.put("photoshop", photoshopmetadata);
        BufferedImage thumbnail = jpegMetadata.getEXIFThumbnail();
        metadataH.put("hasEXIFThumbnail", null != thumbnail);

        Map<String, Object> jpegMetadataH = new HashMap<String, Object>();
        metadataH.put("jpegMetadata", jpegMetadataH);

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

        // 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();

                jpegMetadataH.put("GPSDescription", gpsDescription);
                jpegMetadataH.put("GPSLongitude", longitude);
                jpegMetadataH.put("GPSLatitude", latitude);
            }
            List<TiffField> allFields = exifMetadata.getAllFields();
            List<Map<String, Object>> allFieldsL = new ArrayList<Map<String, Object>>();
            jpegMetadataH.put("allFields", allFieldsL);
            if (null != allFields) {
                for (TiffField field : allFields) {
                    Map<String, Object> fieldH = new HashMap<String, Object>();
                    allFieldsL.add(fieldH);
                    fieldH.put("fieldType", field.getFieldTypeName());
                    if (field.getFieldType().equals(FieldType.RATIONAL)) {
                        // These fields format oddly, must be strings
                        fieldH.put("value", field.getValue().toString());
                    }
                    fieldH.put("descriptionWithoutValue", field.getDescriptionWithoutValue());
                    fieldH.put("directoryType", field.getDirectoryType());
                    fieldH.put("tagName", field.getTagName());
                    fieldH.put("valueDescription", field.getValueDescription());
                }
            }
        }

        // 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

            Map<String, Object> gpsH = new HashMap<String, Object>();
            jpegMetadataH.put("gps", gpsH);
            Map<String, Object> gpsLatitudeH = new HashMap<String, Object>();
            Map<String, Object> gpsLongitudeH = new HashMap<String, Object>();
            gpsH.put("latitude", gpsLatitudeH);
            gpsH.put("longitude", gpsLongitudeH);

            gpsLatitudeH.put("degrees", gpsLatitudeDegrees.toDisplayString());
            gpsLatitudeH.put("minutes", gpsLatitudeMinutes.toDisplayString());
            gpsLatitudeH.put("seconds", gpsLatitudeSeconds.toDisplayString());
            gpsLatitudeH.put("display", gpsLatitudeRef);
            gpsLongitudeH.put("degrees", gpsLongitudeDegrees.toDisplayString());
            gpsLongitudeH.put("minutes", gpsLongitudeMinutes.toDisplayString());
            gpsLongitudeH.put("seconds", gpsLongitudeSeconds.toDisplayString());
            gpsLongitudeH.put("display", gpsLongitudeRef);

        }
    }
    return metadataH;
}

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

/**
 * Creates metadata from image metadata/*  w  w w  .j  a v a2 s  .  c om*/
 * 
 * @param imageMetadata
 *            Can be <code>null</code> when not available
 * @return
 */
private PhotoImageMetadata createPhotoMetadata(final IImageMetadata imageMetadata) {

    final PhotoImageMetadata photoMetadata = new PhotoImageMetadata();

    /*
     * read meta data for this photo
     */
    if (imageMetadata instanceof TiffImageMetadata) {

        photoMetadata.isExifFromImage = true;

        final TiffImageMetadata tiffMetadata = (TiffImageMetadata) imageMetadata;

        photoMetadata.exifDateTime = getTiffValueDate(tiffMetadata);

        photoMetadata.orientation = 1;

        photoMetadata.imageWidth = getTiffValueInt(tiffMetadata, TiffTagConstants.TIFF_TAG_IMAGE_WIDTH,
                Integer.MIN_VALUE);

        photoMetadata.imageHeight = getTiffValueInt(tiffMetadata, TiffTagConstants.TIFF_TAG_IMAGE_LENGTH,
                Integer.MIN_VALUE);

        photoMetadata.model = getTiffValueString(tiffMetadata, TiffTagConstants.TIFF_TAG_MODEL);

    } else if (imageMetadata instanceof JpegImageMetadata) {

        photoMetadata.isExifFromImage = true;

        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) imageMetadata;

        photoMetadata.exifDateTime = getExifValueDate(jpegMetadata);

        photoMetadata.orientation = getExifValueInt(jpegMetadata, TiffTagConstants.TIFF_TAG_ORIENTATION, 1);

        photoMetadata.imageWidth = getExifValueInt(jpegMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_WIDTH,
                Integer.MIN_VALUE);

        photoMetadata.imageHeight = getExifValueInt(jpegMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_LENGTH,
                Integer.MIN_VALUE);

        photoMetadata.imageDirection = getExifValueDouble(jpegMetadata,
                GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION);

        photoMetadata.altitude = getExifValueDouble(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE);

        photoMetadata.model = getExifValueString(jpegMetadata, TiffTagConstants.TIFF_TAG_MODEL);

        /*
         * GPS
         */
        final TiffImageMetadata exifMetadata = jpegMetadata.getExif();
        if (exifMetadata != null) {

            try {
                final TiffImageMetadata.GPSInfo gpsInfo = exifMetadata.getGPS();
                if (gpsInfo != null) {

                    photoMetadata.latitude = gpsInfo.getLatitudeAsDegreesNorth();
                    photoMetadata.longitude = gpsInfo.getLongitudeAsDegreesEast();
                }
            } catch (final Exception e) {
                // ignore
            }
        }
        photoMetadata.gpsAreaInfo = getExifValueGpsArea(jpegMetadata);

        /*
         * photoshop metadata
         */
        final JpegPhotoshopMetadata pshopMetadata = jpegMetadata.getPhotoshop();
        if (pshopMetadata != null) {

            final List<? extends IImageMetadataItem> pshopItems = pshopMetadata.getItems();

            for (final IImageMetadataItem pshopItem : pshopItems) {

                if (pshopItem instanceof Item) {

                    final Item item = (Item) pshopItem;
                    final String keyword = item.getKeyword();

                    if (keyword.equals(IptcTypes.OBJECT_NAME.name)) {

                        photoMetadata.objectName = item.getText();

                    } else if (keyword.equals(IptcTypes.CAPTION_ABSTRACT.name)) {
                        photoMetadata.captionAbstract = item.getText();
                    }
                }
            }

        }
    }

    // set file date time
    photoMetadata.fileDateTime = _imageFileLastModified;

    //// this will log all available meta data
    //      System.out.println(UI.timeStampNano());
    //      System.out.println(UI.timeStampNano() + " " + imageFileName);
    //      System.out.println(UI.timeStampNano());
    //      System.out.println(imageMetadata.toString());
    //      System.out.println(UI.timeStampNano());
    //      System.out.println(photoMetadata);
    //      System.out.println(UI.timeStampNano());
    //      // TODO remove SYSTEM.OUT.PRINTLN

    return photoMetadata;
}

From source file:net.tourbook.tour.photo.TourPhotoManager.java

/**
 * This example illustrates how to set the GPS values in JPEG EXIF metadata.
 * //from  w ww. j a va2  s.  co m
 * @param jpegImageFile
 *            A source image file.
 * @param destinationFile
 *            The output file.
 * @param latitude
 * @param longitude
 * @throws IOException
 * @throws ImageReadException
 * @throws ImageWriteException
 */
private void setExifGPSTag_IntoImageFile_WithExifRewriter(final File jpegImageFile, final File destinationFile,
        final double latitude, final double longitude)
        throws IOException, ImageReadException, ImageWriteException {

    OutputStream os = null;

    try {

        TiffOutputSet outputSet = null;

        // note that metadata might be null if no metadata is found.
        final IImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

        if (null != jpegMetadata) {

            // note that exif might be null if no Exif metadata is found.
            final TiffImageMetadata exif = jpegMetadata.getExif();

            if (null != exif) {
                // TiffImageMetadata class is immutable (read-only).
                // TiffOutputSet class represents the Exif data to write.
                //
                // Usually, we want to update existing Exif metadata by
                // changing
                // the values of a few fields, or adding a field.
                // In these cases, it is easiest to use getOutputSet() to
                // start with a "copy" of the fields read from the image.
                outputSet = exif.getOutputSet();
            }
        }

        // if file does not contain any exif metadata, we create an empty
        // set of exif metadata. Otherwise, we keep all of the other
        // existing tags.
        if (null == outputSet) {
            outputSet = new TiffOutputSet();
        }

        {
            // Example of how to add/update GPS info to output set.

            // New York City
            //            final double longitude = -74.0; // 74 degrees W (in Degrees East)
            //            final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
            // North)

            outputSet.setGPSInDegrees(longitude, latitude);
        }

        os = new FileOutputStream(destinationFile);
        os = new BufferedOutputStream(os);

        /**
         * the lossless method causes an exception after 3 times writing the image file,
         * therefore the lossy method is used
         * 
         * <pre>
         * 
         * org.apache.commons.imaging.formats.jpeg.exif.ExifRewriter$ExifOverflowException: APP1 Segment is too long: 65564
         *    at org.apache.commons.imaging.formats.jpeg.exif.ExifRewriter.writeSegmentsReplacingExif(ExifRewriter.java:552)
         *    at org.apache.commons.imaging.formats.jpeg.exif.ExifRewriter.updateExifMetadataLossless(ExifRewriter.java:393)
         *    at org.apache.commons.imaging.formats.jpeg.exif.ExifRewriter.updateExifMetadataLossless(ExifRewriter.java:293)
         *    at net.tourbook.photo.PhotosAndToursView.setExifGPSTag_IntoPhoto(PhotosAndToursView.java:2309)
         *    at net.tourbook.photo.PhotosAndToursView.setExifGPSTag(PhotosAndToursView.java:2141)
         * 
         * </pre>
         */
        //         new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);
        //         new ExifRewriter().updateExifMetadataLossy(jpegImageFile, os, outputSet);

        os.close();
        os = null;
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (final IOException e) {

            }
        }
    }
}

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.
        ////  w w  w.  j av a2 s . c o 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.apache.commons.imaging.examples.WriteExifMetadataExample.java

/**
 * This example illustrates how to add/update EXIF metadata in a JPEG file.
 * //from   w  w  w. j a  v a2s.co  m
 * @param jpegImageFile
 *            A source image file.
 * @param dst
 *            The output file.
 * @throws IOException
 * @throws ImageReadException
 * @throws ImageWriteException
 */
public void changeExifMetadata(final File jpegImageFile, final File dst)
        throws IOException, ImageReadException, ImageWriteException {

    try (FileOutputStream fos = new FileOutputStream(dst); OutputStream os = new BufferedOutputStream(fos);) {

        TiffOutputSet outputSet = null;

        // note that metadata might be null if no metadata is found.
        final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
        if (null != jpegMetadata) {
            // note that exif might be null if no Exif metadata is found.
            final TiffImageMetadata exif = jpegMetadata.getExif();

            if (null != exif) {
                // TiffImageMetadata class is immutable (read-only).
                // TiffOutputSet class represents the Exif data to write.
                //
                // Usually, we want to update existing Exif metadata by
                // changing
                // the values of a few fields, or adding a field.
                // In these cases, it is easiest to use getOutputSet() to
                // start with a "copy" of the fields read from the image.
                outputSet = exif.getOutputSet();
            }
        }

        // if file does not contain any exif metadata, we create an empty
        // set of exif metadata. Otherwise, we keep all of the other
        // existing tags.
        if (null == outputSet) {
            outputSet = new TiffOutputSet();
        }

        {
            // Example of how to add a field/tag to the output set.
            //
            // Note that you should first remove the field/tag if it already
            // exists in this directory, or you may end up with duplicate
            // tags. See above.
            //
            // Certain fields/tags are expected in certain Exif directories;
            // Others can occur in more than one directory (and often have a
            // different meaning in different directories).
            //
            // TagInfo constants often contain a description of what
            // directories are associated with a given tag.
            //
            final TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory();
            // make sure to remove old value if present (this method will
            // not fail if the tag does not exist).
            exifDirectory.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
            exifDirectory.add(ExifTagConstants.EXIF_TAG_APERTURE_VALUE, new RationalNumber(3, 10));
        }

        {
            // Example of how to add/update GPS info to output set.

            // New York City
            final double longitude = -74.0; // 74 degrees W (in Degrees East)
            final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
            // North)

            outputSet.setGPSInDegrees(longitude, latitude);
        }

        // printTagValue(jpegMetadata, TiffConstants.TIFF_TAG_DATE_TIME);

        new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);
    }
}