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:at.ac.tuwien.qse.sepm.dao.repo.impl.JpegSerializer.java

@Override
public void update(InputStream is, OutputStream os, PhotoMetadata metadata) throws DAOException {
    if (is == null)
        throw new IllegalArgumentException();
    if (os == null)
        throw new IllegalArgumentException();
    if (metadata == null)
        throw new IllegalArgumentException();
    LOGGER.debug("updating photo metadata {}", metadata);

    String tags = "travelimg";

    for (Tag element : metadata.getTags()) {
        tags += "/" + element.getName();
    }/* www  . j a  va  2  s  . c o  m*/

    Rating rating = metadata.getRating();
    tags += "/rating|" + rating;

    Place place = metadata.getPlace();
    if (place != null) {
        tags += "/place|" + place.getCity() + "|" + place.getCountry() + "|" + place.getLatitude() + "|"
                + place.getLongitude();
    }

    Journey journey = metadata.getJourney();
    if (journey != null) {
        tags += "/journey|" + journey.getName() + "|" + journey.getStartDate().format(DATE_FORMATTER) + "|"
                + journey.getEndDate().format(DATE_FORMATTER);
    }

    Photographer photographer = metadata.getPhotographer();
    if (photographer != null) {
        tags += "/photographer|" + photographer.getName();
    }

    try {
        is.mark(Integer.MAX_VALUE);
        ImageMetadata imageData = Imaging.getMetadata(is, null);
        if (imageData == null) {
            LOGGER.debug("could not find image metadata");
            throw new DAOException("No metadata found.");
        }
        if (!(imageData instanceof JpegImageMetadata)) {
            LOGGER.debug("metadata is of unknown type");
            throw new DAOException("Metadata is of unknown type.");
        }

        JpegImageMetadata jpegData = (JpegImageMetadata) imageData;
        TiffOutputSet outputSet = new TiffOutputSet();
        TiffImageMetadata exifData = jpegData.getExif();
        if (exifData != null) {
            outputSet = exifData.getOutputSet();
        }

        TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory();
        outputSet.setGPSInDegrees(metadata.getLongitude(), metadata.getLatitude());

        exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
        exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL,
                DATE_FORMATTER.format(metadata.getDatetime()));

        exifDirectory.removeField(ExifTagConstants.EXIF_TAG_USER_COMMENT);
        exifDirectory.add(ExifTagConstants.EXIF_TAG_USER_COMMENT, tags);

        is.reset();
        new ExifRewriter().updateExifMetadataLossless(is, os, outputSet);

    } catch (IOException | ImageReadException | ImageWriteException ex) {
        LOGGER.warn("failed updating metadata");
        throw new DAOException(ex);
    }

    LOGGER.debug("updated photo metadata");
}

From source file:com.att.aro.ui.model.ImageBPTable.java

private StringBuffer extractMetadata(String fullpath) {
    ImageMetadata metadata;/* w  w w .  j a  va 2  s.co  m*/
    String imgMetadata = "";
    StringBuffer completeMetadata = new StringBuffer();
    // List<? extends ImageMetadataItem> imgMdata;
    try {
        metadata = Imaging.getMetadata(new File(fullpath));

        if (metadata != null) {
            if (!metadata.getClass().equals(GenericImageMetadata.class)) {
                JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
                TiffImageMetadata exif = jpegMetadata.getExif();
                if (exif != null) {

                    for (int i = 0; i < exif.getItems().size(); i++) {
                        imgMetadata = exif.getItems().get(i).toString();
                        completeMetadata.append(imgMetadata);
                        completeMetadata.append("\n");
                    }

                }
            } else {
                GenericImageMetadata genMetadata = (GenericImageMetadata) metadata;
                if (genMetadata.getItems() != null && genMetadata.getItems().size() > 5) {

                    for (int i = 0; i < genMetadata.getItems().size(); i++) {
                        imgMetadata = genMetadata.getItems().get(i).toString();

                        completeMetadata.append(imgMetadata);
                        completeMetadata.append("\n");
                    }

                }
            }
        }

    } catch (IOException | ImageReadException e) {
        e.printStackTrace();
    }

    return completeMetadata;

}

From source file:com.hygenics.imaging.ImageCleanup.java

public byte[] writeMetaData(String data, byte[] ibytes) {
    // write metadata based on the metadata columns list
    TiffOutputSet outset = null;//  ww w  . j av a2 s.  c om
    BufferedImage bi;
    ImageMetadata metadata;
    ByteArrayOutputStream bos = null;
    try {

        // get the buffered image to write to
        bi = Imaging.getBufferedImage(ibytes);
        metadata = Imaging.getMetadata(ibytes);
        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

        if (null != jpegMetadata) {
            // get the image exif data
            TiffImageMetadata exif = jpegMetadata.getExif();
            outset = exif.getOutputSet();
        }

        if (outset == null) {
            // get a new set (directory structured to write to)
            outset = new TiffOutputSet();
        }

        TiffOutputDirectory exdir = outset.getOrCreateExifDirectory();
        exdir.removeField(ExifTagConstants.EXIF_TAG_USER_COMMENT);

        exdir.add(ExifTagConstants.EXIF_TAG_USER_COMMENT, data.trim());

        bos = new ByteArrayOutputStream();
        ByteArrayInputStream bis = new ByteArrayInputStream(ibytes);

        ExifRewriter exrw = new ExifRewriter();

        // read to a byte stream
        exrw.updateExifMetadataLossy(bis, bos, outset);

        // read the input from the byte buffer
        ibytes = bos.toByteArray();
        bis.close();
        bos.close();

    } catch (ImageReadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ImageWriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return ibytes;
}

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

/**
 * Processes the incoming data./* ww  w.  ja v  a  2  s .  co  m*/
 *
 * @param input   the input to process
 * @param errors   for storing errors
 * @return      the generated output
 */
@Override
protected Boolean doProcess(Object input, MessageCollection errors) {
    Boolean result;
    File inputFile;
    JpegImageMetadata meta;
    TiffImageMetadata exif;

    result = false;

    if (input instanceof String)
        inputFile = new PlaceholderFile((String) input).getAbsoluteFile();
    else
        inputFile = ((File) input).getAbsoluteFile();

    try {
        meta = (JpegImageMetadata) Imaging.getMetadata(inputFile);
        if (meta != null) {
            exif = meta.getExif();
            if (exif != null) {
                result = (exif.getFieldValue(m_Tag.getTagInfo()) != null);
            } 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);
    }

    return result;
}

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

/**
 * Processes the incoming data./*from ww  w. ja v a 2 s  . com*/
 *
 * @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;
    JpegImageMetadata meta;
    TiffImageMetadata exif;

    result = null;

    if (input instanceof String)
        inputFile = new PlaceholderFile((String) input).getAbsoluteFile();
    else
        inputFile = ((File) input).getAbsoluteFile();

    try {
        meta = (JpegImageMetadata) Imaging.getMetadata(inputFile);
        if (meta != null) {
            exif = meta.getExif();
            if (exif != null) {
                result = exif.getFieldValue(m_Tag.getTagInfo());
            } 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);
    }

    return result;
}

From source file:com.ubb.imaging.ExifMetadataWriter.java

/**
 * This method illustrates how to set the GPS values in JPEG EXIF metadata.
 * /*  w  w  w.  j a  v  a  2  s .com*/
 * @param jpegImageFile
 *            A source image file.
 * @param dst
 *            The output file.
 * @throws IOException
 * @throws ImageReadException
 * @throws ImageWriteException
 */
public void setExifGPSTag(final File jpegImageFile, final File dst)
        throws IOException, ImageReadException, ImageWriteException {
    OutputStream os = null;
    boolean canThrow = false;
    try {
        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/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(dst);
        os = new BufferedOutputStream(os);

        new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);
        canThrow = true;
    } finally {
        IoUtils.closeQuietly(canThrow, os);
    }
}

From source file:com.ubb.imaging.ExifMetadataWriter.java

public void readMetadata(File file) throws ImageReadException {
    ImageMetadata metadata = null;/*w ww .j av a 2  s.com*/

    try {
        metadata = (ImageMetadata) Imaging.getMetadata(file);

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

            System.out.println("==============================" + "\nReading From the File: " + file.getPath());
            System.out.println("==============================");

            System.out.print(jpegMetadata.getExif());
        }

    } catch (ImageReadException | IOException e) {
        e.printStackTrace();
    }

}

From source file:com.ubb.imaging.ExifMetadataWriter.java

/**
 * This method illustrates how to add/update EXIF metadata in a JPEG file.
 * /*w  w w  .  j  a  v a  2 s. com*/
 * @param srcFile
 *            A source image file.
 * @param imageId
 * @param dstFile
 *            The output file.
 * @throws IOException
 * @throws ImageReadException
 * @throws ImageWriteException
 */
public void changeExifMetadata(File srcFile, File dstFile, String imageId)
        throws IOException, ImageReadException, ImageWriteException {
    OutputStream os = null;
    boolean canThrow = false;
    try {
        TiffOutputSet outputSet = null;

        // note that metadata might be null if no metadata is found.
        final ImageMetadata metadata = (ImageMetadata) Imaging.getMetadata(srcFile);
        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.
            //
            // see
            // org.apache.commons.imaging.formats.tiff.constants.AllTagConstants
            //

            final TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory();

            updateImageUniqueId(exifDirectory, imageId);
            updateDocumentName(exifDirectory, imageId);
            updateUserComments(exifDirectory);
            updateImageDescription(exifDirectory, LINK_TO_RESOURCE.concat(imageId));

            // AllTagConstants.TIFF_TAG_IMAGE_DESCRIPTION
            // AllTagConstants.TIFF_TAG_DOCUMENT_NAME
            // AllTagConstants.TIFF_TAG_COPYRIGHT   

        }

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

        new ExifRewriter().updateExifMetadataLossless(srcFile, os, outputSet);

        canThrow = true;
    } finally {
        IoUtils.closeQuietly(canThrow, os);

        //delete the source file
        srcFile.delete();
        //move the new file with new metadata to the source file path (it's like copy and delete).
        FileUtils.moveFile(dstFile, srcFile);

    }
}

From source file:de.tehame.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  a  v a2 s .com
        // 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:lucee.runtime.img.Metadata.java

private static void fill(String format, InputStream is, Struct info) throws ImageReadException, IOException {
    // get all metadata stored in EXIF format (ie. from JPEG or TIFF).
    IImageMetadata metadata = Imaging.getMetadata(is, "test." + format);
    if (metadata == null)
        return;//  w  w w  .  j a  v  a  2 s.c o  m

    // System.out.println(metadata);

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

        try {
            set(jpegMetadata.getItems(), info, null);
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
        }
        try {
            set(metadata.getItems(), info, null);
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
        }

        // Photoshop
        if (metadata instanceof JpegImageMetadata) {
            JpegPhotoshopMetadata photoshop = ((JpegImageMetadata) metadata).getPhotoshop();
            if (photoshop != null) {
                try {

                    List<? extends IImageMetadataItem> list = photoshop.getItems();
                    if (list != null && !list.isEmpty()) {
                        Struct ps = new StructImpl();
                        info.setEL("photoshop", ps);
                        try {
                            set(list, ps, null);
                        } catch (Throwable t) {
                            ExceptionUtil.rethrowIfNecessary(t);
                        }
                    }
                } catch (Throwable t) {
                    ExceptionUtil.rethrowIfNecessary(t);
                }
            }
        }

        // EXIF
        if (jpegMetadata != null) {
            Struct exif = new StructImpl();
            info.setEL("exif", exif);
            try {
                set(jpegMetadata.getExif().getItems(), exif, null);
            } catch (Throwable t) {
                ExceptionUtil.rethrowIfNecessary(t);
            }
        }
        // GPS
        try {
            gps(jpegMetadata, info);
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
        }

    }
}