Ejemplo n.º 1
0
  public static Integer readImageOrientation(File imageFile) {
    Metadata metadata = null;
    try {
      metadata = ImageMetadataReader.readMetadata(imageFile);
    } catch (Exception e) {
      // Any exception here is handled as if image
      // format doesn't support EXIF
      return null;
    }

    Directory directory = metadata.getDirectory(ExifIFD0Directory.class);
    JpegDirectory jpegDirectory = (JpegDirectory) metadata.getDirectory(JpegDirectory.class);

    int orientation = 1;

    try {
      orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
      /*int width = jpegDirectory.getImageWidth();
      int height = jpegDirectory.getImageHeight();*/
    } catch (Exception e) {
      Logger.warn("Could not get orientation");
    }

    return orientation;
  }
Ejemplo n.º 2
0
 private void processFile(File file) throws IOException {
   String fileEx = FileUtility.getFileExtension(file);
   Data data;
   if (fileEx.equals(".jpg") || fileEx.equals(".jpeg")) {
     Metadata meta = null;
     Date[] dates = null;
     try {
       meta = ImageMetadataReader.readMetadata(file);
       dates = PhotoUtility.getData(meta);
     } catch (ImageProcessingException e) {
     } catch (TagNotFound e) {
     } finally {
       if (meta != null && dates != null) data = new Data(file, dates[0], ImageType.JPG, false);
       else data = new Data(file, new Date(file.lastModified()), ImageType.JPG, true);
     }
   } else
     data =
         new Data(
             file,
             new Date(file.lastModified()),
             ImageType.valueOf(fileEx.substring(1).toUpperCase()),
             true);
   notifyFileCountObservers(CountType.SINGEL, ++count);
   notifyImageObservers(data);
 }
 // ----------------------------------------------------------------------------------------------------
 private long _readExifDate(File jpegFile) {
   try {
     Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
     ExifSubIFDDirectory dir = metadata.getDirectory(ExifSubIFDDirectory.class);
     Date d = dir.getDate(36868);
     return d.getTime();
   } catch (Exception e) {
     return -1;
   }
 }
 // ----------------------------------------------------------------------------------------------------
 private String _readExifDateStr(File jpegFile) {
   try {
     Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
     ExifSubIFDDirectory dir = metadata.getDirectory(ExifSubIFDDirectory.class);
     Date d = dir.getDate(36868);
     return m_sdf.format(d);
   } catch (Exception e) {
     return "_0000-00-00_";
   }
 }
Ejemplo n.º 5
0
  /**
   * 将一个文件转化为 PicMetaInfo 对象
   *
   * @param file
   * @return
   */
  public PicMetaInfo toPicMetaInfo(File file) {
    PicMetaInfo picMetaInfo = null;
    try {
      Metadata metadata = ImageMetadataReader.readMetadata(file);
      picMetaInfo = picInfoReader.toPicMetaInfo(metadata, file);

      return picMetaInfo;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  private void scanPictures(String filePath, boolean shared) {
    File file = new File(filePath);

    ContentValues values = new ContentValues();

    String mime = "image/" + FilenameUtils.getExtension(filePath);
    fillCommonValues(values, Constants.FILE_TYPE_PICTURES, filePath, file, mime, shared);

    try {
      Metadata metadata = ImageMetadataReader.readMetadata(file);

      ExifIFD0Directory dir = metadata.getDirectory(ExifIFD0Directory.class);
      ExifIFD0Descriptor desc = new ExifIFD0Descriptor(dir);

      String title = desc.getWindowsTitleDescription();
      if (StringUtils.isNullOrEmpty(title, true)) {
        title = FilenameUtils.getBaseName(file.getName());
      }

      String artist = desc.getWindowsAuthorDescription();
      if (StringUtils.isNullOrEmpty(artist, true)) {
        artist = dir.getString(ExifIFD0Directory.TAG_ARTIST, "UTF-8");
      }
      if (StringUtils.isNullOrEmpty(artist, true)) {
        artist = "";
      }

      String album = "";
      String year = dir.getString(ExifIFD0Directory.TAG_DATETIME);
      if (StringUtils.isNullOrEmpty(year, true)) {
        year = "";
      }

      values.put(Columns.TITLE, title);
      values.put(Columns.ARTIST, artist);
      values.put(Columns.ALBUM, album);
      values.put(Columns.YEAR, year);
    } catch (Throwable e) {
      String displayName = FilenameUtils.getBaseName(file.getName());

      values.put(Columns.TITLE, displayName);
      values.put(Columns.ARTIST, "");
      values.put(Columns.ALBUM, "");
      values.put(Columns.YEAR, "");
    }

    ShareFilesDB db = ShareFilesDB.intance();

    db.insert(values);
  }
Ejemplo n.º 7
0
 /**
  * Tries to read the EXIF orientation data in the image in the {@link InputStream}. Returns <code>
  * null</code> if not found or if an error occurs.
  */
 @Nullable
 public static ImageOrientation getOrientation(@Nullable final InputStream inputStream) {
   if (inputStream != null) {
     try {
       return getOrientation(
           ImageMetadataReader.readMetadata(new BufferedInputStream(inputStream), true));
     } catch (Exception e) {
       LOG.info(
           "ImageOrientation.getOrientation(): Exception while trying to read the orientation data from the EXIF.  Ignoring and just returning null"
               + e);
     }
   }
   return null;
 }
Ejemplo n.º 8
0
  /**
   * 打印出单个图片的元信息
   *
   * @throws Exception
   */
  private void printAllMetaInfos() throws Exception {
    String filePath = "E:\\360_sync\\Sync\\Photos\\wallpaper\\DSC07775.JPG";
    Metadata metadata = ImageMetadataReader.readMetadata(new File(filePath));

    for (Directory directory : metadata.getDirectories()) {
      for (Tag tag : directory.getTags()) {
        System.out.format(
            "[%s] - %s = %s\n", directory.getName(), tag.getTagName(), tag.getDescription());
      }
      if (directory.hasErrors()) {
        for (String error : directory.getErrors()) {
          System.err.format("ERROR: %s", error);
        }
      }
    }

    PicMetaInfo info = toPicMetaInfo(new File(filePath));
    System.out.println(info);
  }
Ejemplo n.º 9
0
 protected final Media buildMedia(final MediaUploadBatch context)
     throws MediaReaderException, IOException {
   final String fileName = getFile().getAbsolutePath();
   try {
     final Metadata rawMetadata = ImageMetadataReader.readMetadata(getFile());
     final ExifThumbnailDirectory thumbnailDirectory =
         rawMetadata.getDirectory(ExifThumbnailDirectory.class);
     final byte[] thumbnail;
     if (thumbnailDirectory != null && thumbnailDirectory.hasThumbnailData()) {
       thumbnail = thumbnailDirectory.getThumbnailData();
     } else {
       thumbnail = new byte[0];
     }
     final Map<String, Object> metadata = new HashMap<>(rawMetadata.getDirectoryCount());
     for (final Directory directory : rawMetadata.getDirectories()) {
       copy(directory, metadata);
       preProcess(context, directory, metadata);
     }
     return new Media(getFile(), fileName, context.getTemplate(), metadata, thumbnail);
   } catch (final ImageProcessingException e) {
     throw new MediaReaderException(e);
   }
 }
Ejemplo n.º 10
0
  /**
   * @param filename
   * @return
   */
  private HashMap<String, String> extractExifDatas(String filename) {
    HashMap<String, String> datas = new HashMap<String, String>();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH'h'mm.ss");
    try {
      File jpegFile = new File(filename);
      Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);

      // reading exif
      ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
      if (directory != null) {
        Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
        if (date != null) {
          datas.put("date", formatter.format(date));
        }
      }
    } catch (JpegProcessingException e) {
      System.err.println("Problem during datas extraction : " + e.getMessage());
    } catch (IOException e) {
      System.err.println("Problem during datas extraction" + e.getMessage());
    } catch (ImageProcessingException e) {
      System.err.println("Problem during datas extraction" + e.getMessage());
    }
    return datas;
  }
Ejemplo n.º 11
0
  /**
   * 保持上传照片的图片方向不发生调整
   *
   * @param filePath 图片的文件路径
   */
  public static void MaintainOrientation(String filePath) {
    try {
      File file = new File(filePath);
      if (!file.exists()) {
        logger.fatal(new FileNotFoundException());
        return;
      }

      Metadata metadata = ImageMetadataReader.readMetadata(file);
      Directory directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
      int orientation = 0;
      if (null != directory && directory.containsTag(ExifSubIFDDirectory.TAG_ORIENTATION)) {
        orientation = directory.getInt(ExifSubIFDDirectory.TAG_ORIENTATION);
        logger.debug(filePath + " 's orientation is :" + orientation);
      }
      String format = FileUtil.getFileSuffix(filePath);
      switch (orientation) {
          // case 1:
          // return "Top, left side (Horizontal / normal)";
          // case 2:
          // return "Top, right side (Mirror horizontal)";
        case 3:
          // return "Bottom, right side (Rotate 180)";
          BufferedImage old_img3 = (BufferedImage) ImageIO.read(file);
          int w3 = old_img3.getWidth();
          int h3 = old_img3.getHeight();

          BufferedImage new_img3 = new BufferedImage(w3, h3, BufferedImage.TYPE_INT_BGR);
          Graphics2D g2d3 = new_img3.createGraphics();

          AffineTransform origXform3 = g2d3.getTransform();
          AffineTransform newXform3 = (AffineTransform) (origXform3.clone());
          // center of rotation is center of the panel
          // double xRot3 = w3/2.0;
          newXform3.rotate(Math.toRadians(180.0), w3 / 2.0, h3 / 2.0); // 旋转180度

          g2d3.setTransform(newXform3);
          // draw image centered in panel
          g2d3.drawImage(old_img3, 0, 0, null);
          // Reset to Original
          g2d3.setTransform(origXform3);
          // 写到新的文件
          FileOutputStream out3 = new FileOutputStream(file);
          try {
            ImageIO.write(new_img3, format, out3);
          } finally {
            out3.close();
          }

          break;
          // case 4:
          // return "Bottom, left side (Mirror vertical)";
          // case 5:
          // return "Left side, top (Mirror horizontal and rotate 270
          // CW)";
        case 6:
          // return "Right side, top (Rotate 90 CW)";

          BufferedImage old_img6 = (BufferedImage) ImageIO.read(file);
          int w6 = old_img6.getWidth();
          int h6 = old_img6.getHeight();

          BufferedImage new_img6 = new BufferedImage(h6, w6, BufferedImage.TYPE_INT_BGR);
          Graphics2D g2d6 = new_img6.createGraphics();

          AffineTransform origXform6 = g2d6.getTransform();
          AffineTransform newXform6 = (AffineTransform) (origXform6.clone());
          // center of rotation is center of the panel
          double xRot6 = h6 / 2.0;
          newXform6.rotate(Math.toRadians(90.0), xRot6, xRot6); // 旋转90度

          g2d6.setTransform(newXform6);
          // draw image centered in panel
          g2d6.drawImage(old_img6, 0, 0, null);
          // Reset to Original
          g2d6.setTransform(origXform6);
          // 写到新的文件
          FileOutputStream out6 = new FileOutputStream(file);
          try {
            ImageIO.write(new_img6, format, out6);
          } finally {
            out6.close();
          }

          break;
          // case 7:
          // return "Right side, bottom (Mirror horizontal and rotate 90
          // CW)";
        case 8:
          // return "Left side, bottom (Rotate 270 CW)";
          BufferedImage old_img8 = (BufferedImage) ImageIO.read(file);
          int w8 = old_img8.getWidth();
          int h8 = old_img8.getHeight();

          BufferedImage new_img8 = new BufferedImage(h8, w8, BufferedImage.TYPE_INT_BGR);
          Graphics2D g2d8 = new_img8.createGraphics();

          AffineTransform origXform8 = g2d8.getTransform();
          AffineTransform newXform8 = (AffineTransform) (origXform8.clone());
          // center of rotation is center of the panel
          double xRot8 = w8 / 2.0;
          newXform8.rotate(Math.toRadians(270.0), xRot8, xRot8); // 旋转90度

          g2d8.setTransform(newXform8);
          // draw image centered in panel
          g2d8.drawImage(old_img8, 0, 0, null);
          // Reset to Original
          g2d8.setTransform(origXform8);
          // 写到新的文件
          FileOutputStream out8 = new FileOutputStream(file);
          try {
            ImageIO.write(new_img8, format, out8);
          } finally {
            out8.close();
          }

          break;
          // default:
          // return String.valueOf(orientation);
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.fatal(e);
    }
  }
Ejemplo n.º 12
0
  /**
   * Executes the sample usage program.
   *
   * @param args command line parameters
   */
  public static void main(String[] args) {
    File file = new File("Tests/Data/withIptcExifGps.jpg");

    // There are multiple ways to get a Metadata object for a file

    //
    // SCENARIO 1: UNKNOWN FILE TYPE
    //
    // This is the most generic approach.  It will transparently determine the file type and invoke
    // the appropriate
    // readers.  In most cases, this is the most appropriate usage.  This will handle JPEG, TIFF,
    // GIF, BMP and RAW
    // (CRW/CR2/NEF/RW2/ORF) files and extract whatever metadata is available and understood.
    //
    try {
      Metadata metadata = ImageMetadataReader.readMetadata(file);

      print(metadata);
    } catch (ImageProcessingException e) {
      // handle exception
    } catch (IOException e) {
      // handle exception
    }

    //
    // SCENARIO 2: SPECIFIC FILE TYPE
    //
    // If you know the file to be a JPEG, you may invoke the JpegMetadataReader, rather than the
    // generic reader
    // used in approach 1.  Similarly, if you knew the file to be a TIFF/RAW image you might use
    // TiffMetadataReader,
    // PngMetadataReader for PNG files, BmpMetadataReader for BMP files, or GifMetadataReader for
    // GIF files.
    //
    // Using the specific reader offers a very, very slight performance improvement.
    //
    try {
      Metadata metadata = JpegMetadataReader.readMetadata(file);

      print(metadata);
    } catch (JpegProcessingException e) {
      // handle exception
    } catch (IOException e) {
      // handle exception
    }

    //
    // APPROACH 3: SPECIFIC METADATA TYPE
    //
    // If you only wish to read a subset of the supported metadata types, you can do this by
    // passing the set of readers to use.
    //
    // This currently only applies to JPEG file processing.
    //
    try {
      // We are only interested in handling
      Iterable<JpegSegmentMetadataReader> readers =
          Arrays.asList(new ExifReader(), new IptcReader());

      Metadata metadata = JpegMetadataReader.readMetadata(file, readers);

      print(metadata);
    } catch (JpegProcessingException e) {
      // handle exception
    } catch (IOException e) {
      // handle exception
    }
  }
Ejemplo n.º 13
0
 /**
  * Reads filename and store in private variables
  *
  * @param filename
  * @throws ImageProcessingException
  * @throws IOException
  */
 public void readImageFile(String filename) throws ImageProcessingException, IOException {
   File jpegFile = new File(filename);
   this.metadata = ImageMetadataReader.readMetadata(jpegFile);
   this.directory = (ExifSubIFDDirectory) metadata.getDirectory(ExifSubIFDDirectory.class);
 }
Ejemplo n.º 14
0
 /**
  * Constructor call with a parameter needed
  *
  * @param jpegFile
  * @throws ImageProcessingException
  * @throws IOException
  */
 public EXIFMetadataExtractor(File jpegFile) throws ImageProcessingException, IOException {
   this.metadata = ImageMetadataReader.readMetadata(jpegFile);
   this.directory = (ExifSubIFDDirectory) metadata.getDirectory(ExifSubIFDDirectory.class);
 }
  /**
   * An application entry point. Takes the name of one or more files as arguments and prints the
   * contents of all metadata directories to <code>System.out</code>.
   *
   * <p>If <code>-thumb</code> is passed, then any thumbnail data will be written to a file with
   * name of the input file having <code>.thumb.jpg</code> appended.
   *
   * <p>If <code>-markdown</code> is passed, then output will be in markdown format.
   *
   * <p>If <code>-hex</code> is passed, then the ID of each tag will be displayed in hexadecimal.
   *
   * @param args the command line arguments
   */
  public static void main(@NotNull String[] args) throws MetadataException, IOException {
    Collection<String> argList = new ArrayList<String>(Arrays.asList(args));
    boolean thumbRequested = argList.remove("-thumb");
    boolean markdownFormat = argList.remove("-markdown");
    boolean showHex = argList.remove("-hex");

    if (argList.size() < 1) {
      String version = ImageMetadataReader.class.getPackage().getImplementationVersion();
      System.out.println("metadata-extractor version " + version);
      System.out.println();
      System.out.println(
          String.format(
              "Usage: java -jar metadata-extractor-%s.jar <filename> [<filename>] [-thumb] [-markdown] [-hex]",
              version == null ? "a.b.c" : version));
      System.exit(1);
    }

    for (String filePath : argList) {
      long startTime = System.nanoTime();
      File file = new File(filePath);

      if (!markdownFormat && argList.size() > 1)
        System.out.printf("\n***** PROCESSING: %s\n%n", filePath);

      Metadata metadata = null;
      try {
        metadata = ImageMetadataReader.readMetadata(file);
      } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(1);
      }
      long took = System.nanoTime() - startTime;
      if (!markdownFormat)
        System.out.printf(
            "Processed %.3f MB file in %.2f ms%n%n",
            file.length() / (1024d * 1024), took / 1000000d);

      if (markdownFormat) {
        String fileName = file.getName();
        String urlName = StringUtil.urlEncode(filePath);
        ExifIFD0Directory exifIFD0Directory =
            metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
        String make =
            exifIFD0Directory == null
                ? ""
                : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MAKE);
        String model =
            exifIFD0Directory == null
                ? ""
                : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MODEL);
        System.out.println();
        System.out.println("---");
        System.out.println();
        System.out.printf("# %s - %s%n", make, model);
        System.out.println();
        System.out.printf(
            "<a href=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\">%n",
            urlName);
        System.out.printf(
            "<img src=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\" width=\"300\"/><br/>%n",
            urlName);
        System.out.println(fileName);
        System.out.println("</a>");
        System.out.println();
        System.out.println("Directory | Tag Id | Tag Name | Extracted Value");
        System.out.println(":--------:|-------:|----------|----------------");
      }

      // iterate over the metadata and print to System.out
      for (Directory directory : metadata.getDirectories()) {
        String directoryName = directory.getName();
        for (Tag tag : directory.getTags()) {
          String tagName = tag.getTagName();
          String description = tag.getDescription();

          // truncate the description if it's too long
          if (description != null && description.length() > 1024) {
            description = description.substring(0, 1024) + "...";
          }

          if (markdownFormat) {
            System.out.printf(
                "%s|0x%s|%s|%s%n",
                directoryName, Integer.toHexString(tag.getTagType()), tagName, description);
          } else {
            // simple formatting
            if (showHex) {
              System.out.printf(
                  "[%s - %s] %s = %s%n", directoryName, tag.getTagTypeHex(), tagName, description);
            } else {
              System.out.printf("[%s] %s = %s%n", directoryName, tagName, description);
            }
          }
        }

        // print out any errors
        for (String error : directory.getErrors()) System.err.println("ERROR: " + error);
      }

      if (args.length > 1 && thumbRequested) {
        ExifThumbnailDirectory directory =
            metadata.getFirstDirectoryOfType(ExifThumbnailDirectory.class);
        if (directory != null && directory.hasThumbnailData()) {
          System.out.println("Writing thumbnail...");
          directory.writeThumbnail(args[0].trim() + ".thumb.jpg");
        } else {
          System.out.println("No thumbnail data exists in this image");
        }
      }
    }
  }