Example usage for org.apache.commons.imaging Imaging getMetadata

List of usage examples for org.apache.commons.imaging Imaging getMetadata

Introduction

In this page you can find the example usage for org.apache.commons.imaging Imaging getMetadata.

Prototype

private static IImageMetadata getMetadata(final ByteSource byteSource, final Map<String, Object> params)
            throws ImageReadException, IOException 

Source Link

Usage

From source file:lucee.runtime.img.Metadata.java

private static void fillExif(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 2s.  c om*/
    if (metadata instanceof JpegImageMetadata) {
        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

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

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.
        ///*ww w . j av a 2s. 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:at.ac.tuwien.qse.sepm.dao.repo.impl.JpegSerializer.java

@Override
public PhotoMetadata read(InputStream is) throws DAOException {
    if (is == null)
        throw new IllegalArgumentException();
    LOGGER.debug("reading metadata");

    ImageMetadata imageData;//from   w  ww. ja  v a2s.  c  o m
    try {
        imageData = Imaging.getMetadata(is, null);
    } catch (ImageReadException | IOException ex) {
        LOGGER.warn("failed reading metadata");
        throw new FormatException(ex);
    }

    PhotoMetadata result = new PhotoMetadata();
    if (imageData == null) {
        LOGGER.debug("could not find image metadata");
        return result;
    }

    if (!(imageData instanceof JpegImageMetadata)) {
        LOGGER.debug("metadata is of unknown type");
        return result;
    }

    JpegImageMetadata jpegData = (JpegImageMetadata) imageData;
    readDate(jpegData, result);
    readGps(jpegData, result);
    readMetaData(jpegData, result);
    return result;
}

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;/*  ww  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);
        }

    }
}

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();
    }/*from   w  w  w  . j a va  2s .com*/

    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:net.tourbook.photo.Photo.java

/**
 * Updated metadata from the image file/*w w  w .  j  a  v  a2 s  . com*/
 * 
 * @param isReadThumbnail
 * @return Returns image metadata <b>with</b> image thumbnail <b>only</b> when
 *         <code>isReadThumbnail</code> is <code>true</code>, otherwise it checks if metadata
 *         are already loaded.
 */
public IImageMetadata getImageMetaData(final Boolean isReadThumbnail) {

    if (_photoImageMetadata != null && isReadThumbnail == false) {

        // meta data are available but the exif thumnail is not requested

        return null;
    }

    if (PhotoLoadManager.isImageLoadingError(imageFilePathName)) {
        // image could not be loaded previously
        return null;
    }

    IImageMetadata imageFileMetadata = null;

    try {

        /*
         * read metadata WITH thumbnail image info, this is the default when the pamameter is
         * ommitted
         */
        final HashMap<String, Object> params = new HashMap<String, Object>();
        params.put(ImagingConstants.PARAM_KEY_READ_THUMBNAILS, isReadThumbnail);

        //         final long start = System.currentTimeMillis();

        imageFileMetadata = Imaging.getMetadata(imageFile, params);

        //         System.out.println(UI.timeStamp()
        //               + Thread.currentThread().getName()
        //               + "read exif\t"
        //               + ((System.currentTimeMillis() - start) + " ms")
        //               + ("\tWithThumb: " + isReadThumbnail)
        //               + ("\t" + imageFilePathName)
        //         //
        //               );
        //         // TODO remove SYSTEM.OUT.PRINTLN
        //
        //         System.out.println(imageFileMetadata);
        //         // TODO remove SYSTEM.OUT.PRINTLN

    } catch (final Exception e) {

        StatusUtil.log(NLS.bind(//
                "Could not read metadata from image \"{0}\"", //$NON-NLS-1$
                imageFile));

        PhotoLoadManager.putPhotoInLoadingErrorMap(imageFilePathName);

    } finally {

        final PhotoImageMetadata photoImageMetadata = createPhotoMetadata(imageFileMetadata);

        updateImageMetadata(photoImageMetadata);
    }

    return imageFileMetadata;
}

From source file:org.openstreetmap.josm.plugins.mapillary.utils.ImageImportUtil.java

/**
 * @param is the input stream to read the metadata from
 * @param f the file that will be set as a field to the returned {@link MapillaryImportedImage}
 * @param defaultLL the coordinates that the image should get, if no coordinates are found in metadata
 * @return the {@link MapillaryImportedImage} with the read metadata and the given file set
 * @throws IOException if an IOException occurs while reading from the input stream
 *///from  ww w .  ja va2s.  c om
private static MapillaryImportedImage readImageFrom(final InputStream is, final File f, final LatLon defaultLL)
        throws IOException {
    Object latRef = null;
    Object lonRef = null;
    Object lat = null;
    Object lon = null;
    Object gpsDir = null;
    Object dateTime = null;
    final ImageMetadata meta;
    try {
        meta = Imaging.getMetadata(is, null);
        if (meta instanceof JpegImageMetadata) {
            final JpegImageMetadata jpegMeta = (JpegImageMetadata) meta;
            latRef = getTiffFieldValue(jpegMeta, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
            lonRef = getTiffFieldValue(jpegMeta, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
            lat = getTiffFieldValue(jpegMeta, GpsTagConstants.GPS_TAG_GPS_LATITUDE);
            lon = getTiffFieldValue(jpegMeta, GpsTagConstants.GPS_TAG_GPS_LONGITUDE);
            gpsDir = getTiffFieldValue(jpegMeta, GpsTagConstants.GPS_TAG_GPS_IMG_DIRECTION);
            dateTime = getTiffFieldValue(jpegMeta, ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
        }
    } catch (ImageReadException e) {
        // Can't read metadata from image, use defaults instead
    }

    final LatLon latLon;
    if (lat instanceof RationalNumber[] && latRef != null && lon instanceof RationalNumber[]
            && lonRef != null) {
        latLon = new LatLon(MapillaryUtils.degMinSecToDouble((RationalNumber[]) lat, latRef.toString()),
                MapillaryUtils.degMinSecToDouble((RationalNumber[]) lon, lonRef.toString()));
    } else {
        latLon = defaultLL;
    }
    final double ca;
    if (gpsDir instanceof RationalNumber) {
        ca = ((RationalNumber) gpsDir).doubleValue();
    } else {
        ca = 0;
    }
    if (dateTime == null) {
        return new MapillaryImportedImage(latLon, ca, f);
    }
    return new MapillaryImportedImage(latLon, ca, f, dateTime.toString());
}

From source file:oulib.aws.s3.S3Util.java

/**
 *  Get exif technical metadata from S3 object
 * //from   w  w  w . j a v a2 s.c o  m
 * @param s3client
 * @param s3
 * @return : TiffImageMetadata
 */
public static TiffImageMetadata retrieveExifMetadata(AmazonS3 s3client, S3Object s3) {
    TiffImageMetadata tiffMetadata = null;
    try {
        S3ObjectInputStream is = s3.getObjectContent();
        final ImageMetadata metadata = Imaging.getMetadata(is, s3.getKey());
        tiffMetadata = (TiffImageMetadata) metadata;
    } catch (ImageReadException | IOException ex) {
        Logger.getLogger(S3Util.class.getName()).log(Level.SEVERE, null, ex);
    }
    return tiffMetadata;
}

From source file:slash.navigation.photo.PhotoFormat.java

public void read(InputStream source, ParserContext<Wgs84Route> context) throws Exception {
    BufferedInputStream bufferedSource = new BufferedInputStream(source, READ_BUFFER_SIZE);
    bufferedSource.mark(READ_BUFFER_SIZE);

    Dimension size = Imaging.getImageSize(bufferedSource, null);
    if (size == null)
        return;/*from   w  w w  .j a  v  a 2s  .c  o  m*/

    PhotoPosition position = new PhotoPosition(NotTaggable, context.getStartDate(), "No EXIF data", null);

    bufferedSource.reset();
    ImageMetadata metadata = Imaging.getMetadata(bufferedSource, null);
    TiffImageMetadata tiffImageMetadata = extractTiffImageMetadata(metadata);
    if (tiffImageMetadata != null) {
        @SuppressWarnings("unchecked")
        List<Directory> directories = (List<Directory>) tiffImageMetadata.getDirectories();
        for (Directory directory : directories)
            log.info("Reading EXIF directory " + directory);

        extendPosition(position, tiffImageMetadata, context.getStartDate());
    }

    bufferedSource.reset();
    File image = context.getFile();
    if (image == null)
        image = extractToTempFile(bufferedSource);
    position.setOrigin(image);
    position.setWaypointType(Photo);
    context.appendRoute(new Wgs84Route(this, Waypoints, new ArrayList<Wgs84Position>(singletonList(position))));
}