com.drew.metadata.Metadata Java Examples

The following examples show how to use com.drew.metadata.Metadata. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PngMetadataReader.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull InputStream inputStream) throws PngProcessingException, IOException
{
    Iterable<PngChunk> chunks = new PngChunkReader().extract(new StreamReader(inputStream), _desiredChunkTypes);

    Metadata metadata = new Metadata();

    for (PngChunk chunk : chunks) {
        try {
            processChunk(metadata, chunk);
        } catch (Exception e) {
            metadata.addDirectory(new ErrorDirectory("Exception reading PNG chunk: " + e.getMessage()));
        }
    }

    return metadata;
}
 
Example #2
Source File: ExtractImageMetadata.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getTags(Integer max, Metadata metadata) {
    Map<String, String> results = new HashMap<>();
    int i =0;

    for (Directory directory : metadata.getDirectories()) {
        for (Tag tag : directory.getTags()) {
            results.put(directory.getName() + "." + tag.getTagName(), tag.getDescription());

            if(max!=null) {
                i++;
                if (i >= max) {
                    return results;
                }
            }
        }
    }

    return results;
}
 
Example #3
Source File: ProcessAllImagesInFolderUtility.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
    super.onExtractionSuccess(file, metadata, relativePath, log);

    String extension = getExtension(file);

    if (extension == null) {
        return;
    }

    // Sanitise the extension
    extension = extension.toLowerCase();
    if (_extensionEquivalence.containsKey(extension))
        extension = _extensionEquivalence.get(extension);

    List<Row> list = _rowListByExtension.get(extension);
    if (list == null) {
        list = new ArrayList<Row>();
        _rowListByExtension.put(extension, list);
    }
    list.add(new Row(file, metadata, relativePath));
}
 
Example #4
Source File: ExifReaderTest.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
@Test
public void testDifferenceImageAndThumbnailOrientations() throws Exception
{
    // This metadata contains different orientations for the thumbnail and the main image.
    // These values used to be merged into a single directory, causing errors.
    // This unit test demonstrates correct behaviour.
    Metadata metadata = processBytes("Tests/Data/repeatedOrientationTagWithDifferentValues.jpg.app1");
    ExifIFD0Directory ifd0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
    ExifThumbnailDirectory thumbnailDirectory = metadata.getFirstDirectoryOfType(ExifThumbnailDirectory.class);

    assertNotNull(ifd0Directory);
    assertNotNull(thumbnailDirectory);

    assertEquals(1, ifd0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION));
    assertEquals(8, thumbnailDirectory.getInt(ExifThumbnailDirectory.TAG_ORIENTATION));
}
 
Example #5
Source File: QuickTimeMediaHandler.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
public QuickTimeMediaHandler(Metadata metadata, QuickTimeContext context)
{
    super(metadata);

    if (context.creationTime != null && context.modificationTime != null) {
        // Get creation/modification times
        directory.setDate(
            QuickTimeMediaDirectory.TAG_CREATION_TIME,
            DateUtil.get1Jan1904EpochDate(context.creationTime)
        );
        directory.setDate(
            QuickTimeMediaDirectory.TAG_MODIFICATION_TIME,
            DateUtil.get1Jan1904EpochDate(context.modificationTime)
        );
    }
}
 
Example #6
Source File: JpegDnlReader.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
public void extract(byte[] segmentBytes, Metadata metadata, JpegSegmentType segmentType)
{
    JpegDirectory directory = metadata.getFirstDirectoryOfType(JpegDirectory.class);
    if (directory == null) {
        ErrorDirectory errorDirectory = new ErrorDirectory();
        metadata.addDirectory(errorDirectory);
        errorDirectory.addError("DNL segment found without SOFx - illegal JPEG format");
        return;
    }

    SequentialReader reader = new SequentialByteArrayReader(segmentBytes);

    try {
        // Only set height from DNL if it's not already defined
        Integer i = directory.getInteger(JpegDirectory.TAG_IMAGE_HEIGHT);
        if (i == null || i == 0) {
            directory.setInt(JpegDirectory.TAG_IMAGE_HEIGHT, reader.getUInt16());
        }
    } catch (IOException ex) {
        directory.addError(ex.getMessage());
    }
}
 
Example #7
Source File: XmpReaderTest.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    Metadata metadata = new Metadata();
    List<byte[]> jpegSegments = new ArrayList<byte[]>();
    jpegSegments.add(FileUtil.readBytes("Tests/Data/withXmpAndIptc.jpg.app1.1"));
    new XmpReader().readJpegSegments(jpegSegments, metadata, JpegSegmentType.APP1);

    Collection<XmpDirectory> xmpDirectories = metadata.getDirectoriesOfType(XmpDirectory.class);

    assertNotNull(xmpDirectories);
    assertEquals(1, xmpDirectories.size());

    _directory = xmpDirectories.iterator().next();

    assertFalse(_directory.hasErrors());
}
 
Example #8
Source File: Mp4HandlerFactory.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
public Mp4Handler<?> getHandler(HandlerBox box, Metadata metadata, Mp4Context context)
{
    String type = box.getHandlerType();
    if (type.equals(HANDLER_SOUND_MEDIA)) {
        return new Mp4SoundHandler(metadata, context);
    } else if (type.equals(HANDLER_VIDEO_MEDIA)) {
        return new Mp4VideoHandler(metadata, context);
    } else if (type.equals(HANDLER_HINT_MEDIA)) {
        return new Mp4HintHandler(metadata, context);
    } else if (type.equals(HANDLER_TEXT_MEDIA)) {
        return new Mp4TextHandler(metadata, context);
    } else if (type.equals(HANDLER_META_MEDIA)) {
        return new Mp4MetaHandler(metadata, context);
    }
    return caller;
}
 
Example #9
Source File: EpsMetadataReader.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull File file) throws IOException
{
    Metadata metadata = new Metadata();

    FileInputStream stream = new FileInputStream(file);

    try {
        new EpsReader().extract(stream, metadata);
    } finally {
        stream.close();
    }

    new FileSystemMetadataReader().read(file, metadata);
    return metadata;
}
 
Example #10
Source File: QuickTimeHandlerFactory.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
public QuickTimeHandler<?> getHandler(String type, Metadata metadata, QuickTimeContext context)
{
    if (type.equals(HANDLER_METADATA_DIRECTORY)) {
        return new QuickTimeDirectoryHandler(metadata);
    } else if (type.equals(HANDLER_METADATA_DATA)) {
        return new QuickTimeDataHandler(metadata);
    } else if (type.equals(HANDLER_SOUND_MEDIA)) {
        return new QuickTimeSoundHandler(metadata, context);
    } else if (type.equals(HANDLER_VIDEO_MEDIA)) {
        return new QuickTimeVideoHandler(metadata, context);
    } else if (type.equals(HANDLER_TIMECODE_MEDIA)) {
        return new QuickTimeTimecodeHandler(metadata, context);
    } else if (type.equals(HANDLER_TEXT_MEDIA)) {
        return new QuickTimeTextHandler(metadata, context);
    } else if (type.equals(HANDLER_SUBTITLE_MEDIA)) {
        return new QuickTimeSubtitleHandler(metadata, context);
    } else if (type.equals(HANDLER_MUSIC_MEDIA)) {
        return new QuickTimeMusicHandler(metadata, context);
    }
    return caller;
}
 
Example #11
Source File: Mp3MetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull InputStream inputStream)
{
    Metadata metadata = new Metadata();
    new Mp3Reader().extract(inputStream, metadata);
    return metadata;
}
 
Example #12
Source File: IptcReaderTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static IptcDirectory processBytes(@NotNull String filePath) throws IOException
{
    Metadata metadata = new Metadata();
    byte[] bytes = FileUtil.readBytes(filePath);
    new IptcReader().extract(new SequentialByteArrayReader(bytes), metadata, bytes.length);
    IptcDirectory directory = metadata.getFirstDirectoryOfType(IptcDirectory.class);
    assertNotNull(directory);
    return directory;
}
 
Example #13
Source File: ProcessAllImagesInFolderUtility.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
private static void processDirectory(@NotNull File path, @NotNull FileHandler handler, @NotNull String relativePath, PrintStream log)
{
    handler.onStartingDirectory(path);

    String[] pathItems = path.list();

    if (pathItems == null) {
        return;
    }

    // Order alphabetically so that output is stable across invocations
    Arrays.sort(pathItems);

    for (String pathItem : pathItems) {
        File file = new File(path, pathItem);

        if (file.isDirectory()) {
            processDirectory(file, handler, relativePath.length() == 0 ? pathItem : relativePath + "/" + pathItem, log);
        } else if (handler.shouldProcess(file)) {

            handler.onBeforeExtraction(file, log, relativePath);

            // Read metadata
            final Metadata metadata;
            try {
                metadata = ImageMetadataReader.readMetadata(file);
            } catch (Throwable t) {
                handler.onExtractionError(file, t, log);
                continue;
            }

            handler.onExtractionSuccess(file, metadata, relativePath, log);
        }
    }
}
 
Example #14
Source File: ResourceAction.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Map getImgMetadata(File file) {
    logger.debug("Get image Metadata in Resource Action");
    Map<String, String> meta = new HashMap<>();
    ResourceInterface resourcePrototype = this.getResourceManager().createResourceType(this.getResourceType());
    try {
        Metadata metadata = ImageMetadataReader.readMetadata(file);
        String ignoreKeysConf = resourcePrototype.getMetadataIgnoreKeys();
        String[] ignoreKeys = null;
        if (null != ignoreKeysConf) {
            ignoreKeys = ignoreKeysConf.split(",");
            logger.debug("Metadata ignoreKeys: {}", ignoreKeys);
        } else {
            logger.debug("Metadata ignoreKeys not configured");
        }
        List<String> ignoreKeysList = new ArrayList<String>();
        if (null != ignoreKeys) {
            ignoreKeysList = Arrays.asList(ignoreKeys);
        }
        for (Directory directory : metadata.getDirectories()) {
            for (Tag tag : directory.getTags()) {
                if (!ignoreKeysList.contains(tag.getTagName())) {
                    logger.debug("Add Metadata with key: {}", tag.getTagName());
                    meta.put(tag.getTagName(), tag.getDescription());
                } else {
                    logger.debug("Skip Metadata key {}", tag.getTagName());
                }
            }
        }
    } catch (ImageProcessingException ex) {
        logger.error("Error reading metadata from file " + this.getFileName() + " - message " + ex.getMessage());
    } catch (IOException ioex) {
        logger.error("Error reading file", ioex);
    }
    return meta;
}
 
Example #15
Source File: PngMetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull File file) throws PngProcessingException, IOException
{
    InputStream inputStream = new FileInputStream(file);
    Metadata metadata;
    try {
        metadata = readMetadata(inputStream);
    } finally {
        inputStream.close();
    }
    new FileSystemMetadataReader().read(file, metadata);
    return metadata;
}
 
Example #16
Source File: ExifReaderTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadJpegSegmentWithNoExifData() throws Exception
{
    byte[] badExifData = new byte[]{ 1,2,3,4,5,6,7,8,9,10 };
    Metadata metadata = new Metadata();
    ArrayList<byte[]> segments = new ArrayList<byte[]>();
    segments.add(badExifData);
    new ExifReader().readJpegSegments(segments, metadata, JpegSegmentType.APP1);
    assertEquals(0, metadata.getDirectoryCount());
    assertFalse(metadata.hasErrors());
}
 
Example #17
Source File: ExifDirectoryTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@Test
public void testDateTime() throws JpegProcessingException, IOException, MetadataException
{
    Metadata metadata = ExifReaderTest.processBytes("Tests/Data/nikonMakernoteType2a.jpg.app1");

    ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
    ExifSubIFDDirectory exifSubIFDDirectory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);

    assertNotNull(exifIFD0Directory);
    assertNotNull(exifSubIFDDirectory);

    assertEquals("2003:10:15 10:37:08", exifIFD0Directory.getString(ExifIFD0Directory.TAG_DATETIME));
    assertEquals("80", exifSubIFDDirectory.getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME));
    assertEquals("2003:10:15 10:37:08", exifSubIFDDirectory.getString(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL));
    assertEquals("80", exifSubIFDDirectory.getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME_ORIGINAL));
    assertEquals("2003:10:15 10:37:08", exifSubIFDDirectory.getString(ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED));
    assertEquals("80", exifSubIFDDirectory.getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME_DIGITIZED));

    assertEquals(1066214228800L, exifIFD0Directory.getDate(
        ExifIFD0Directory.TAG_DATETIME,
        exifSubIFDDirectory.getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME),
        null
    ).getTime());
    assertEquals(1066210628800L, exifIFD0Directory.getDate(
        ExifIFD0Directory.TAG_DATETIME,
        exifSubIFDDirectory.getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME),
        TimeZone.getTimeZone("GMT+0100")
    ).getTime());

    assertEquals(1066214228800L, exifSubIFDDirectory.getDateModified().getTime());
    assertEquals(1066210628800L, exifSubIFDDirectory.getDateModified(TimeZone.getTimeZone("GMT+0100")).getTime());
    assertEquals(1066214228800L, exifSubIFDDirectory.getDateOriginal().getTime());
    assertEquals(1066210628800L, exifSubIFDDirectory.getDateOriginal(TimeZone.getTimeZone("GMT+0100")).getTime());
    assertEquals(1066214228800L, exifSubIFDDirectory.getDateDigitized().getTime());
    assertEquals(1066210628800L, exifSubIFDDirectory.getDateDigitized(TimeZone.getTimeZone("GMT+0100")).getTime());
}
 
Example #18
Source File: QuickTimeMetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull InputStream inputStream)
{
    Metadata metadata = new Metadata();
    QuickTimeReader.extract(inputStream, new QuickTimeAtomHandler(metadata));
    return metadata;
}
 
Example #19
Source File: JpegMetadataReaderTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
private void validate(Metadata metadata)
{
    Directory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
    assertNotNull(directory);
    assertEquals("80", directory.getString(ExifSubIFDDirectory.TAG_ISO_EQUIVALENT));
    directory = metadata.getFirstDirectoryOfType(HuffmanTablesDirectory.class);
    assertNotNull(directory);
    assertTrue(((HuffmanTablesDirectory) directory).isOptimized());
}
 
Example #20
Source File: ImageDataReader.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static ImageInfo getImageInfo(InputStream imageStream) throws ImageProcessingException, IOException {
    Metadata metadata = ImageMetadataReader.readMetadata(imageStream);
    ImageInfo.Builder builder = new ImageInfo.Builder();
    for (Directory directory: metadata.getDirectories()) {
        for (Tag tag: directory.getTags()) {
            if (ParsingUtils.IMAGE_HEIGHT.equals(tag.getTagName())) {
                builder.setPixelsY(ParsingUtils.getIntegerFromData(tag.getDescription()));
            } else if (ParsingUtils.IMAGE_WIDTH.equals(tag.getTagName())) {
                builder.setPixelsX(ParsingUtils.getIntegerFromData(tag.getDescription()));
            }
        }
    }
    return builder.build();
}
 
Example #21
Source File: EpsReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes a commented hex section, and uses {@link IccReader} to decode the resulting data.
 */
private static void extractIccData(@NotNull final Metadata metadata, @NotNull SequentialReader reader) throws IOException
{
    byte[] buffer = decodeHexCommentBlock(reader);

    if (buffer != null)
        new IccReader().extract(new ByteArrayReader(buffer), metadata);
}
 
Example #22
Source File: Mp4MetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull InputStream inputStream) throws IOException
{
    Metadata metadata = new Metadata();
    Mp4Reader.extract(inputStream, new Mp4BoxHandler(metadata));
    return metadata;
}
 
Example #23
Source File: Mp4MetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull final File file) throws ImageProcessingException, IOException
{
    InputStream inputStream = new FileInputStream(file);
    Metadata metadata;
    try {
        metadata = readMetadata(inputStream);
    } finally {
        inputStream.close();
    }
    new FileSystemMetadataReader().read(file, metadata);
    return metadata;
}
 
Example #24
Source File: XmpReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if there is an extended XMP section based on the standard XMP part.
 * The xmpNote:HasExtendedXMP attribute contains the GUID of the Extended XMP chunks.
 */
@Nullable
private static String getExtendedXMPGUID(@NotNull Metadata metadata)
{
    final Collection<XmpDirectory> xmpDirectories = metadata.getDirectoriesOfType(XmpDirectory.class);

    for (XmpDirectory directory : xmpDirectories) {
        final XMPMeta xmpMeta = directory.getXMPMeta();

        try {
            final XMPIterator itr = xmpMeta.iterator(SCHEMA_XMP_NOTES, null, null);
            if (itr == null)
                continue;

            while (itr.hasNext()) {
                final XMPPropertyInfo pi = (XMPPropertyInfo) itr.next();
                if (ATTRIBUTE_EXTENDED_XMP.equals(pi.getPath())) {
                    return pi.getValue();
                }
            }
        } catch (XMPException e) {
            // Fail silently here: we had a reading issue, not a decoding issue.
        }
    }

    return null;
}
 
Example #25
Source File: HeifMetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull InputStream inputStream)
{
    Metadata metadata = new Metadata();
    new HeifReader().extract(inputStream, new HeifBoxHandler(metadata));
    return metadata;
}
 
Example #26
Source File: ProcessAllImagesInFolderUtility.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
    super.onExtractionSuccess(file, metadata, relativePath, log);

    // Iterate through all values, calling toString to flush out any formatting exceptions
    for (Directory directory : metadata.getDirectories()) {
        directory.getName();
        for (Tag tag : directory.getTags()) {
            tag.getTagName();
            tag.getDescription();
        }
    }
}
 
Example #27
Source File: WavMetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull File file) throws IOException, RiffProcessingException
{
    InputStream inputStream = new FileInputStream(file);
    Metadata metadata;
    try {
        metadata = readMetadata(inputStream);
    } finally {
        inputStream.close();
    }
    new FileSystemMetadataReader().read(file, metadata);
    return metadata;
}
 
Example #28
Source File: MutableImage.java    From react-native-camera-face-detector with MIT License 5 votes vote down vote up
private Metadata originalImageMetaData() throws ImageProcessingException, IOException {
    if(this.originalImageMetaData == null) {//this is expensive, don't do it more than once
        originalImageMetaData = ImageMetadataReader.readMetadata(
                new BufferedInputStream(new ByteArrayInputStream(originalImageData)),
                originalImageData.length
        );
    }
    return originalImageMetaData;
}
 
Example #29
Source File: JpegDhtReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
/**
 * Performs the DHT tables extraction, adding found tables to the specified
 * instance of {@link Metadata}.
 */
public void extract(@NotNull final SequentialReader reader, @NotNull final Metadata metadata)
{
    HuffmanTablesDirectory directory = metadata.getFirstDirectoryOfType(HuffmanTablesDirectory.class);
    if (directory == null) {
        directory = new HuffmanTablesDirectory();
        metadata.addDirectory(directory);
    }

    try {
        while (reader.available() > 0) {
            byte header = reader.getByte();
            HuffmanTableClass tableClass = HuffmanTableClass.typeOf((header & 0xF0) >> 4);
            int tableDestinationId = header & 0xF;

            byte[] lBytes = getBytes(reader, 16);
            int vCount = 0;
            for (byte b : lBytes) {
                vCount += (b & 0xFF);
            }
            byte[] vBytes = getBytes(reader, vCount);
            directory.getTables().add(new HuffmanTable(tableClass, tableDestinationId, lBytes, vBytes));
        }
    } catch (IOException me) {
        directory.addError(me.getMessage());
    }

    directory.setInt(HuffmanTablesDirectory.TAG_NUMBER_OF_TABLES, directory.getTables().size());
}
 
Example #30
Source File: AviMetadataReader.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Metadata readMetadata(@NotNull File file) throws IOException, RiffProcessingException
{
    InputStream inputStream = new FileInputStream(file);
    Metadata metadata;
    try {
        metadata = readMetadata(inputStream);
    } finally {
        inputStream.close();
    }
    new FileSystemMetadataReader().read(file, metadata);
    return metadata;
}