Java Code Examples for com.drew.metadata.Metadata#getFirstDirectoryOfType()

The following examples show how to use com.drew.metadata.Metadata#getFirstDirectoryOfType() . 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: MutableImage.java    From react-native-camera-face-detector with MIT License 6 votes vote down vote up
public void fixOrientation() throws ImageMutationFailedException {
    try {
        Metadata metadata = originalImageMetaData();

        ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
        if (exifIFD0Directory == null) {
            return;
        } else if (exifIFD0Directory.containsTag(ExifIFD0Directory.TAG_ORIENTATION)) {
            int exifOrientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
            if(exifOrientation != 1) {
                rotate(exifOrientation);
                exifIFD0Directory.setInt(ExifIFD0Directory.TAG_ORIENTATION, 1);
            }
        }
    } catch (ImageProcessingException | IOException | MetadataException e) {
        throw new ImageMutationFailedException("failed to fix orientation", e);
    }
}
 
Example 2
Source File: PsdReaderTest.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
@NotNull
public static PsdHeaderDirectory processBytes(@NotNull String file) throws Exception
{
    Metadata metadata = new Metadata();
    InputStream stream = new FileInputStream(new File(file));
    try {
        new PsdReader().extract(new StreamReader(stream), metadata);
    } catch (Exception e) {
        stream.close();
        throw e;
    }

    PsdHeaderDirectory directory = metadata.getFirstDirectoryOfType(PsdHeaderDirectory.class);
    assertNotNull(directory);
    return directory;
}
 
Example 3
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 4
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 5
Source File: FileSystemMetadataReader.java    From metadata-extractor with Apache License 2.0 6 votes vote down vote up
public void read(@NotNull File file, @NotNull Metadata metadata) throws IOException
{
    if (!file.isFile())
        throw new IOException("File object must reference a file");
    if (!file.exists())
        throw new IOException("File does not exist");
    if (!file.canRead())
        throw new IOException("File is not readable");

    FileSystemDirectory directory = metadata.getFirstDirectoryOfType(FileSystemDirectory.class);

    if (directory == null) {
        directory = new FileSystemDirectory();
        metadata.addDirectory(directory);
    }

    directory.setString(FileSystemDirectory.TAG_FILE_NAME, file.getName());
    directory.setLong(FileSystemDirectory.TAG_FILE_SIZE, file.length());
    directory.setDate(FileSystemDirectory.TAG_FILE_MODIFIED_DATE, new Date(file.lastModified()));
}
 
Example 6
Source File: ExifDirectoryTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolution() throws JpegProcessingException, IOException, MetadataException
{
    Metadata metadata = ExifReaderTest.processBytes("Tests/Data/withUncompressedRGBThumbnail.jpg.app1");

    ExifThumbnailDirectory thumbnailDirectory = metadata.getFirstDirectoryOfType(ExifThumbnailDirectory.class);
    assertNotNull(thumbnailDirectory);
    assertEquals(72, thumbnailDirectory.getInt(ExifThumbnailDirectory.TAG_X_RESOLUTION));

    ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
    assertNotNull(exifIFD0Directory);
    assertEquals(216, exifIFD0Directory.getInt(ExifIFD0Directory.TAG_X_RESOLUTION));
}
 
Example 7
Source File: GifReaderTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static GifHeaderDirectory processBytes(@NotNull String file) throws Exception
{
    Metadata metadata = new Metadata();
    InputStream stream = new FileInputStream(file);
    new GifReader().extract(new StreamReader(stream), metadata);
    stream.close();

    GifHeaderDirectory directory = metadata.getFirstDirectoryOfType(GifHeaderDirectory.class);
    assertNotNull(directory);
    return directory;
}
 
Example 8
Source File: JpegReaderTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@NotNull
public static JpegDirectory processBytes(String filePath) throws IOException
{
    Metadata metadata = new Metadata();
    new JpegReader().extract(FileUtil.readBytes(filePath), metadata, JpegSegmentType.SOF0);

    JpegDirectory directory = metadata.getFirstDirectoryOfType(JpegDirectory.class);
    assertNotNull(directory);
    return directory;
}
 
Example 9
Source File: IccReaderTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtract_ProfileDateTime() throws Exception
{
    byte[] app2Bytes = FileUtil.readBytes("Tests/Data/withExifAndIptc.jpg.app2");

    Metadata metadata = new Metadata();
    new IccReader().readJpegSegments(Arrays.asList(app2Bytes), metadata, JpegSegmentType.APP2);

    IccDirectory directory = metadata.getFirstDirectoryOfType(IccDirectory.class);

    assertNotNull(directory);
    assertEquals("1998:02:09 06:49:00", directory.getString(IccDirectory.TAG_PROFILE_DATETIME));
    assertEquals(887006940000L, directory.getDate(IccDirectory.TAG_PROFILE_DATETIME).getTime());
}
 
Example 10
Source File: IccReaderTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadJpegSegments_InvalidData() throws Exception
{
    byte[] app2Bytes = FileUtil.readBytes("Tests/Data/iccDataInvalid1.jpg.app2");

    Metadata metadata = new Metadata();
    new IccReader().readJpegSegments(Arrays.asList(app2Bytes), metadata, JpegSegmentType.APP2);

    IccDirectory directory = metadata.getFirstDirectoryOfType(IccDirectory.class);

    assertNotNull(directory);
    assertTrue(directory.hasErrors());
}
 
Example 11
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 12
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 13
Source File: ExifDirectoryTest.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
@Test
public void testGpsDate() throws IOException, MetadataException
{
    Metadata metadata = ExifReaderTest.processBytes("Tests/Data/withPanasonicFaces.jpg.app1");

    GpsDirectory gpsDirectory = metadata.getFirstDirectoryOfType(GpsDirectory.class);
    assertNotNull(gpsDirectory);
    assertEquals("2010:06:24", gpsDirectory.getString(GpsDirectory.TAG_DATE_STAMP));
    assertEquals("10/1 17/1 21/1", gpsDirectory.getString(GpsDirectory.TAG_TIME_STAMP));
    assertEquals(1277374641000L, gpsDirectory.getGpsDate().getTime());
}
 
Example 14
Source File: ProcessAllImagesInFolderUtility.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
Row(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath)
{
    this.file = file;
    this.metadata = metadata;
    this.relativePath = relativePath;

    ExifIFD0Directory ifd0Dir = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
    ExifSubIFDDirectory subIfdDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
    ExifThumbnailDirectory thumbDir = metadata.getFirstDirectoryOfType(ExifThumbnailDirectory.class);
    if (ifd0Dir != null) {
        manufacturer = ifd0Dir.getDescription(ExifIFD0Directory.TAG_MAKE);
        model = ifd0Dir.getDescription(ExifIFD0Directory.TAG_MODEL);
    }
    boolean hasMakernoteData = false;
    if (subIfdDir != null) {
        exifVersion = subIfdDir.getDescription(ExifSubIFDDirectory.TAG_EXIF_VERSION);
        hasMakernoteData = subIfdDir.containsTag(ExifSubIFDDirectory.TAG_MAKERNOTE);
    }
    if (thumbDir != null) {
        Integer width = thumbDir.getInteger(ExifThumbnailDirectory.TAG_IMAGE_WIDTH);
        Integer height = thumbDir.getInteger(ExifThumbnailDirectory.TAG_IMAGE_HEIGHT);
        thumbnail = width != null && height != null
            ? String.format("Yes (%s x %s)", width, height)
            : "Yes";
    }
    for (Directory directory : metadata.getDirectories()) {
        if (directory.getClass().getName().contains("Makernote")) {
            makernote = directory.getName().replace("Makernote", "").trim();
            break;
        }
    }
    if (makernote == null) {
        makernote = hasMakernoteData ? "(Unknown)" : "N/A";
    }
}
 
Example 15
Source File: XmpWriter.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes the XmpDirectory component of <code>Metadata</code> into an <code>OutputStream</code>
 * @param os Destination for the xmp data
 * @param data populated metadata
 * @return serialize success
 */
public static boolean write(OutputStream os, Metadata data) throws XMPException
{
    XmpDirectory dir = data.getFirstDirectoryOfType(XmpDirectory.class);
    if (dir == null)
        return false;
    XMPMeta meta = dir.getXMPMeta();
    SerializeOptions so = new SerializeOptions().setOmitPacketWrapper(true);
    XMPMetaFactory.serialize(meta, os, so);
    return true;
}
 
Example 16
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 17
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 18
Source File: JfifReaderTest.java    From metadata-extractor with Apache License 2.0 4 votes vote down vote up
@Test public void testRead() throws Exception
{
    final byte[] jfifData = new byte[] {
        74,70,73,70,0,
        1,2,
        1,
        0,108,
        0,108,
        0,0
    };

    final Metadata metadata = new Metadata();
    final JfifReader reader = new JfifReader();
    reader.extract(new ByteArrayReader(jfifData), metadata);

    assertEquals(1, metadata.getDirectoryCount());
    JfifDirectory directory = metadata.getFirstDirectoryOfType(JfifDirectory.class);
    assertNotNull(directory);
    assertFalse(directory.getErrors().toString(), directory.hasErrors());

    Tag[] tags = directory.getTags().toArray(new Tag[directory.getTagCount()]);
    assertEquals(6, tags.length);

    assertEquals(JfifDirectory.TAG_VERSION, tags[0].getTagType());
    assertEquals(0x0102, directory.getInt(tags[0].getTagType()));

    assertEquals(JfifDirectory.TAG_UNITS, tags[1].getTagType());
    assertEquals(1, directory.getInt(tags[1].getTagType()));

    assertEquals(JfifDirectory.TAG_RESX, tags[2].getTagType());
    assertEquals(108, directory.getInt(tags[2].getTagType()));

    assertEquals(JfifDirectory.TAG_RESY, tags[3].getTagType());
    assertEquals(108, directory.getInt(tags[3].getTagType()));

    assertEquals(JfifDirectory.TAG_THUMB_WIDTH, tags[4].getTagType());
    assertEquals(0, directory.getInt(tags[4].getTagType()));

    assertEquals(JfifDirectory.TAG_THUMB_HEIGHT, tags[5].getTagType());
    assertEquals(0, directory.getInt(tags[5].getTagType()));
}
 
Example 19
Source File: ImageRecordReader.java    From Bats with Apache License 2.0 4 votes vote down vote up
private void processDirectory(final MapWriter writer, final Directory directory, final Metadata metadata) {
  for (Tag tag : directory.getTags()) {
    try {
      final int tagType = tag.getTagType();
      Object value;
      if (descriptive || isDescriptionTag(directory, tagType)) {
        value = directory.getDescription(tagType);
        if (directory instanceof PngDirectory) {
          if (((PngDirectory) directory).getPngChunkType().areMultipleAllowed()) {
            value = new String[] { (String) value };
          }
        }
      } else {
        value = directory.getObject(tagType);
        if (directory instanceof ExifIFD0Directory && tagType == ExifIFD0Directory.TAG_DATETIME) {
          ExifSubIFDDirectory exifSubIFDDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
          String subsecond = null;
          if (exifSubIFDDir != null) {
            subsecond = exifSubIFDDir.getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME);
          }
          value = directory.getDate(tagType, subsecond, timeZone);
        } else if (directory instanceof ExifSubIFDDirectory) {
          if (tagType == ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL) {
            value = ((ExifSubIFDDirectory) directory).getDateOriginal(timeZone);
          } else if (tagType == ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED) {
            value = ((ExifSubIFDDirectory) directory).getDateDigitized(timeZone);
          }
        } else if (directory instanceof GpsDirectory) {
          if (tagType == GpsDirectory.TAG_LATITUDE) {
            value = ((GpsDirectory) directory).getGeoLocation().getLatitude();
          } else if (tagType == GpsDirectory.TAG_LONGITUDE) {
            value = ((GpsDirectory) directory).getGeoLocation().getLongitude();
          }
        }
        if (isVersionTag(directory, tagType)) {
          value = directory.getString(tagType, "US-ASCII");
        } else if (isDateTag(directory, tagType)) {
          value = directory.getDate(tagType, timeZone);
        }
      }
      writeValue(writer, formatName(tag.getTagName()), value);
    } catch (Exception e) {
      // simply skip this tag
    }
  }
}
 
Example 20
Source File: MetadataUtil.java    From cineast with MIT License 3 votes vote down vote up
/**
 * Reads the {@link Metadata} from the given {@link Path} and returns the first {@link Directory}
 * of the specified type, if present.
 *
 * <p>Note that this is an utility method when one is interested in only one specific
 * {@code Directory}. Use {@code Metadata} and its factory methods
 * (e.g. {@link ImageMetadataReader#readMetadata} if multiple directories or more fine-graded
 * control is needed.
 *
 * @param path a path from which the directory may be read.
 * @param directoryType the {@code Directory} type
 * @param <T> the {@code Directory} type
 * @return an {@link Optional} containing the first {@code Directory} of type {@code T} of the
 *         metadata of the file, if present, otherwise an empty {@code Optional}.
 */
public static <T extends Directory> T getMetadataDirectoryOfType(Path path,
    Class<T> directoryType) {
  Metadata metadata = null;
  try {
    metadata = ImageMetadataReader.readMetadata(path.toFile());
  } catch (ImageProcessingException | IOException e) {
    logger.error("Error while reading exif data of file {}: {}",
        path, LogHelper.getStackTrace(e));
  }
  if(metadata==null){
    return null;
  }
  return metadata.getFirstDirectoryOfType( directoryType );
}