Java Code Examples for com.drew.imaging.ImageMetadataReader

The following examples show how to use com.drew.imaging.ImageMetadataReader. These examples are extracted from open source projects. 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 Project: pattypan   Source File: CreateFilePane.java    License: MIT License 6 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 2
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 3
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 4
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 5
Source Project: localization_nifi   Source File: ExtractImageMetadata.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowfile = session.get();
    if (flowfile == null) {
        return;
    }

    final ComponentLog logger = this.getLogger();
    final AtomicReference<Metadata> value = new AtomicReference<>(null);
    final Integer max = context.getProperty(MAX_NUMBER_OF_ATTRIBUTES).asInteger();

    try {
        session.read(flowfile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                try {
                    Metadata imageMetadata = ImageMetadataReader.readMetadata(in);
                    value.set(imageMetadata);
                } catch (ImageProcessingException ex) {
                    throw new ProcessException(ex);
                }
            }
        });

        Metadata metadata = value.get();
        Map<String, String> results = getTags(max, metadata);

        // Write the results to an attribute
        if (!results.isEmpty()) {
            flowfile = session.putAllAttributes(flowfile, results);
        }

        session.transfer(flowfile, SUCCESS);
    } catch (ProcessException e) {
        logger.error("Failed to extract image metadata from {} due to {}", new Object[]{flowfile, e});
        session.transfer(flowfile, FAILURE);
    }
}
 
Example 6
Source Project: java-11-examples   Source File: ImageDataReader.java    License: 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 7
Source Project: react-native-camera-face-detector   Source File: MutableImage.java    License: 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 8
Source Project: tutorials   Source File: SampleProcessor.java    License: 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 9
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 10
Source Project: metadata-extractor   Source File: XmpSample.java    License: 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 11
Source Project: Pixelitor   Source File: MetaDataPanel.java    License: 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 12
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 13
Source Project: nifi   Source File: ExtractImageMetadata.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowfile = session.get();
    if (flowfile == null) {
        return;
    }

    final ComponentLog logger = this.getLogger();
    final AtomicReference<Metadata> value = new AtomicReference<>(null);
    final Integer max = context.getProperty(MAX_NUMBER_OF_ATTRIBUTES).asInteger();

    try {
        session.read(flowfile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                try {
                    Metadata imageMetadata = ImageMetadataReader.readMetadata(in);
                    value.set(imageMetadata);
                } catch (ImageProcessingException ex) {
                    throw new ProcessException(ex);
                }
            }
        });

        Metadata metadata = value.get();
        Map<String, String> results = getTags(max, metadata);

        // Write the results to an attribute
        if (!results.isEmpty()) {
            flowfile = session.putAllAttributes(flowfile, results);
        }

        session.transfer(flowfile, SUCCESS);
    } catch (ProcessException e) {
        logger.error("Failed to extract image metadata from {} due to {}", new Object[]{flowfile, e});
        session.transfer(flowfile, FAILURE);
    }
}
 
Example 14
Source Project: scrimage   Source File: ImageMetadata.java    License: Apache License 2.0 5 votes vote down vote up
public static ImageMetadata load(ImageSource source) throws IOException {
   try {
      return fromMetadata(ImageMetadataReader.readMetadata(new ByteArrayInputStream(source.read())));
   } catch (ImageProcessingException e) {
      return ImageMetadata.empty;
   }
}
 
Example 15
Source Project: scrimage   Source File: ImageMetadata.java    License: 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 16
Source Project: sejda   Source File: ExifHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static int getRotationBasedOnExifOrientation(Source<?> source) {
    try {
        int orientation = readExifOrientation(ImageMetadataReader.readMetadata(source.getSeekableSource().asNewInputStream()));
        return getRotation(orientation);
    } catch (Throwable e) {
        LOG.warn("Failed reading rotation based on exif orientation: {}", e.getMessage());
        return 0;
    }
}
 
Example 17
Source Project: edslite   Source File: LoadedImage.java    License: 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 18
Source Project: cineast   Source File: MetadataUtil.java    License: 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 );
}