Java Code Examples for com.drew.imaging.ImageMetadataReader#readMetadata()

The following examples show how to use com.drew.imaging.ImageMetadataReader#readMetadata() . 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: MetadataProcessor.java    From FakeImageDetection with GNU General Public License v3.0 6 votes vote down vote up
public MetadataProcessor(File imageFile) {
    this.imageFile = imageFile;
    try {
        data = ImageMetadataReader.readMetadata(imageFile);
    } catch (Exception ex) {
        Logger.getLogger(MetadataProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    for (Directory directory : data.getDirectories()) {
        extracted_data += String.format("----------------------------------------------%15s---------------------------------\n", directory.getName());
        for (Tag tag : directory.getTags()) {
            extracted_data += tag + "\n";
        }
        if (directory.hasErrors()) {
            for (String error : directory.getErrors()) {
                System.err.println("ERROR: " + error);
            }
        }
    }
}
 
Example 2
Source File: ImageResource.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected Map<String, String> getImgMetadata(File file, List<String> ignoreKeysList) {
    logger.debug("Get image Metadata in Resource Action");
    Map<String, String> meta = new HashMap<>();
    try {
        Metadata metadata = ImageMetadataReader.readMetadata(file);

        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|IOException ex) {
        logger.error("Error reading image metadata for file {}", file.getName(), ex);
    }
    return meta;
}
 
Example 3
Source File: MetadataHelper.java    From leafpicrevived with GNU General Public License v3.0 5 votes vote down vote up
public MediaDetailsMap<String, String> getAllDetails(Context context, Media media) {
    MediaDetailsMap<String, String> data = new MediaDetailsMap<String, String>();
    try {
        Metadata metadata = ImageMetadataReader.readMetadata(context.getContentResolver().openInputStream(media.getUri()));
        for (Directory directory : metadata.getDirectories()) {

            for (Tag tag : directory.getTags()) {
                data.put(tag.getTagName(), directory.getObject(tag.getTagType()) + "");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return data;
}
 
Example 4
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 5
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 6
Source File: CreateFilePane.java    From pattypan with MIT License 5 votes vote down vote up
/**
 *
 * @param filePath
 * @return
 */
private String getExifDate(File file) {

  try {
    Metadata metadata = ImageMetadataReader.readMetadata(file);
    Directory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
    int dateTag = ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL;

    if (directory != null && directory.containsTag(dateTag)) {
      Date date = directory.getDate(dateTag, TimeZone.getDefault());
      return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
    } else {
      return "";
    }
  } catch (ImageProcessingException | IOException ex) {
    Session.LOGGER.log(Level.INFO, 
        "Exif error for {0}: {1}",
        new String[]{file.getName(), ex.getLocalizedMessage()}
    );
    return "";
  }
}
 
Example 7
Source File: SampleProcessor.java    From tutorials with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void process(Record record, SingleLaneBatchMaker batchMaker) throws StageException {
  LOG.info("Input record: {}", record);

  FileRef fileRef = record.get("/fileRef").getValueAsFileRef();
  Metadata metadata;
  try {
    metadata = ImageMetadataReader.readMetadata(fileRef.createInputStream(getContext(), InputStream.class));
  } catch (ImageProcessingException | IOException e) {
    String filename = record.get("/fileInfo/filename").getValueAsString();
    LOG.info("Exception getting metadata from {}", filename, e);
    throw new OnRecordErrorException(record, Errors.SAMPLE_02, e);
  }

  for (Directory directory : metadata.getDirectories()) {
    LinkedHashMap<String, Field> listMap = new LinkedHashMap<>();

    for (Tag tag : directory.getTags()) {
      listMap.put(tag.getTagName(), Field.create(tag.getDescription()));
    }

    if (directory.hasErrors()) {
      for (String error : directory.getErrors()) {
        LOG.info("ERROR: {}", error);
      }
    }

    record.set("/" + directory.getName(), Field.createListMap(listMap));
  }

  LOG.info("Output record: {}", record);

  batchMaker.addRecord(record);
}
 
Example 8
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 9
Source File: XmpSample.java    From metadata-extractor with Apache License 2.0 5 votes vote down vote up
private static void xmpSample(InputStream imageStream) throws XMPException, ImageProcessingException, IOException
{
    // Extract metadata from the image
    Metadata metadata = ImageMetadataReader.readMetadata(imageStream);

    // Iterate through any XMP directories we may have received
    for (XmpDirectory xmpDirectory : metadata.getDirectoriesOfType(XmpDirectory.class)) {

        // Usually with metadata-extractor, you iterate a directory's tags. However XMP has
        // a complex structure with many potentially unknown properties. This doesn't map
        // well to metadata-extractor's directory-and-tag model.
        //
        // If you need to use XMP data, access the XMPMeta object directly.
        XMPMeta xmpMeta = xmpDirectory.getXMPMeta();

        XMPIterator itr = xmpMeta.iterator();

        // Iterate XMP properties
        while (itr.hasNext()) {

            XMPPropertyInfo property = (XMPPropertyInfo) itr.next();

            // Print details of the property
            System.out.println(property.getPath() + ": " + property.getValue());
        }
    }
}
 
Example 10
Source File: MetaDataPanel.java    From Pixelitor with GNU General Public License v3.0 5 votes vote down vote up
private static Metadata extractMetadata(File file) {
    Metadata metadata;
    try {
        metadata = ImageMetadataReader.readMetadata(file);
    } catch (ImageProcessingException | IOException e) {
        Messages.showException(e);
        return null;
    }
    return metadata;
}
 
Example 11
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 12
Source File: ImageMetadata.java    From scrimage with Apache License 2.0 5 votes vote down vote up
public static ImageMetadata fromImage(ImmutableImage image) throws IOException {
   try (ByteArrayInputStream stream = new ByteArrayInputStream(image.bytes(PngWriter.NoCompression))) {
      Metadata metadata = ImageMetadataReader.readMetadata(stream);
      return fromMetadata(metadata);
   } catch (ImageProcessingException e) {
      throw new IOException(e);
   }
}
 
Example 13
Source File: LoadedImage.java    From edslite with GNU General Public License v2.0 4 votes vote down vote up
private void loadInitOrientation(Path imagePath)
{
    try
    {
        InputStream s = imagePath.getFile().getInputStream();
        try
        {
            Metadata m = ImageMetadataReader.readMetadata(s);

            for(Directory directory: m.getDirectories())
                if(directory.containsTag(ExifSubIFDDirectory.TAG_ORIENTATION))
                {
                    int orientation = directory.getInt(ExifSubIFDDirectory.TAG_ORIENTATION);
                    switch (orientation)
                    {
                        case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                            _flipX = true;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_180:
                            _rotation = 180;
                            break;
                        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                            _rotation = 180;
                            _flipX = true;
                            break;
                        case ExifInterface.ORIENTATION_TRANSPOSE:
                            _rotation = 90;
                            _flipX = true;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_90:
                            _rotation = 90;
                            break;
                        case ExifInterface.ORIENTATION_TRANSVERSE:
                            _rotation = -90;
                            _flipX = true;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_270:
                            _rotation = -90;
                            break;
                    }
                    break;
                }
        }
        finally
        {
            s.close();
        }
    }
    catch (Exception e)
    {
        if(GlobalConfig.isDebug())
            Logger.log(e);
    }
}
 
Example 14
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 );
}