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

public static IImageMetadata getMetadata(final File file) throws ImageReadException, IOException 

Source Link

Document

Parses the metadata of an image file.

Usage

From source file:it.inserpio.mapillary.gopro.importer.exif.EXIFPropertyReaderTest.java

@Test
@Ignore//  w  w  w  .j a  va2s  .c  om
public void shouldPrintImageMetadata4() {
    try {
        File jpegImageFile = new File("src/test/resources/full/uploadable-images", "G0010043.JPG");

        final IImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
        final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

        System.out.println(jpegMetadata);
    } catch (Exception e) {
        e.printStackTrace();

        Assert.fail();
    }
}

From source file:net.consulion.jeotag.PhotoLoader.java

private static TiffImageMetadata getExif(final File file) {
    TiffImageMetadata exif = null;//w  w  w. j  a v  a2 s  . com
    try {
        final IImageMetadata metadata = Imaging.getMetadata(file);
        if (metadata != null) {
            final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
            exif = jpegMetadata.getExif();
        } else {
            log(Level.WARNING, String.format("No metadata found for file %s", file));
        }

    } catch (final ImageReadException | IOException ex) {
        Logger.getLogger(PhotoLoader.class.getName()).log(Level.SEVERE, null, ex);
    }
    return exif;
}

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

/**
 * This method illustrates how to add/update EXIF metadata in a JPEG file.
 * /* w  w  w . jav  a2  s .c om*/
 * @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:com.hygenics.imaging.ImageCleanup.java

public byte[] writeMetaData(String data, byte[] ibytes) {
    // write metadata based on the metadata columns list
    TiffOutputSet outset = null;//from   w  w  w .  j  a  va 2  s . c  o  m
    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.ApacheCommonsExifTagRemove.java

/**
 * Processes the incoming data.// www  . 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:at.ac.tuwien.qse.sepm.service.impl.ExifServiceImpl.java

@Override
public Exif getExif(Photo photo) throws ServiceException {
    File file = new File(photo.getPath());
    String exposure = "not available";
    double aperture = 0.0;
    double focalLength = 0.0;
    int iso = 0;//from  w ww.  j  a  v  a2  s . co  m
    boolean flash = false;
    String make = "not available";
    String model = "not available";
    double altitude = 0.0;

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

        if (jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_EXPOSURE_TIME) != null) {
            exposure = jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_EXPOSURE_TIME)
                    .getValueDescription().split(" ")[0];
        }

        if (jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_APERTURE_VALUE) != null) {
            aperture = jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_APERTURE_VALUE)
                    .getDoubleValue();
        }
        if (jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_FOCAL_LENGTH) != null) {
            focalLength = jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_FOCAL_LENGTH)
                    .getDoubleValue();
        }
        if (jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_ISO) != null) {
            iso = jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_ISO).getIntValue();
        }

        if (jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_FLASH) != null) {
            flash = jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_FLASH)
                    .getIntValue() != 0;
        }

        if (jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_MAKE) != null) {
            make = jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_MAKE)
                    .getValueDescription();
        }
        if (jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_MODEL) != null) {
            model = jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_MODEL)
                    .getValueDescription();
        }

        if (jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_ALTITUDE) != null) {
            altitude = jpegMetadata.findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_ALTITUDE)
                    .getDoubleValue();
        }

        return new Exif(photo.getId(), exposure, aperture, focalLength, iso, flash, make, model, altitude);
    } catch (IOException | ImageReadException e) {
        throw new ServiceException(e.getMessage(), e);
    }
}

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

/**
 * Processes the incoming data./* ww w.j a  va 2s .  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.data.image.ImageMetaDataHelper.java

/**
 * Reads the meta-data from the file (Commons Imaging).
 *
 * @param file   the file to read the meta-data from
 * @return      the meta-data//from  w  w  w . j a  v a 2 s. co  m
 * @throws Exception   if failed to read meta-data
 */
public static SpreadSheet commons(File file) throws Exception {
    SpreadSheet sheet;
    Row row;
    org.apache.commons.imaging.common.ImageMetadata meta;
    String[] parts;
    String key;
    String value;
    org.apache.commons.imaging.ImageInfo info;
    String infoStr;
    String[] lines;
    HashSet<String> keys;

    sheet = new DefaultSpreadSheet();

    // header
    row = sheet.getHeaderRow();
    row.addCell("K").setContent("Key");
    row.addCell("V").setContent("Value");

    keys = new HashSet<String>();

    // meta-data
    meta = Imaging.getMetadata(file.getAbsoluteFile());
    if (meta != null) {
        for (Object item : meta.getItems()) {
            key = null;
            value = null;
            if (item instanceof ImageMetadata.Item) {
                key = ((ImageMetadata.Item) item).getKeyword().trim();
                value = ((ImageMetadata.Item) item).getText().trim();
            } else {
                parts = item.toString().split(": ");
                if (parts.length == 2) {
                    key = parts[0].trim();
                    value = parts[1].trim();
                }
            }
            if (key != null) {
                if (!keys.contains(key)) {
                    keys.add(key);
                    row = sheet.addRow();
                    row.addCell("K").setContent(key);
                    row.addCell("V").setContent(fixDateTime(Utils.unquote(value)));
                }
            }
        }
    }

    // image info
    info = Imaging.getImageInfo(file.getAbsoluteFile());
    if (info != null) {
        infoStr = info.toString();
        lines = infoStr.split(System.lineSeparator());
        for (String line : lines) {
            parts = line.split(": ");
            if (parts.length == 2) {
                key = parts[0].trim();
                value = parts[1].trim();
                if (!keys.contains(key)) {
                    row = sheet.addRow();
                    row.addCell("K").setContent(key);
                    row.addCell("V").setContent(Utils.unquote(value));
                    keys.add(key);
                }
            }
        }
    }

    return sheet;
}

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

/**
 * Processes the incoming data.//from www  .j av  a2s .  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;
    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.att.aro.ui.model.ImageBPTable.java

private StringBuffer extractMetadata(String fullpath) {
    ImageMetadata metadata;//  w w w. j a  v  a2s.c  o 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;

}