public void testExtractMetadata() throws Exception { File withExif = new File("Source/com/drew/metadata/exif/test/withExif.jpg"); Metadata metadata = JpegMetadataReader.readMetadata(withExif); assertTrue(metadata.containsDirectory(ExifDirectory.class)); Directory directory = metadata.getDirectory(ExifDirectory.class); assertEquals("80", directory.getString(ExifDirectory.TAG_ISO_EQUIVALENT)); }
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; }
@Test public void testExtractMetadataUsingInputStream() throws Exception { File withExif = new File("Tests/com/drew/metadata/exif/withExif.jpg"); InputStream in = new BufferedInputStream(new FileInputStream((withExif))); Metadata metadata = JpegMetadataReader.readMetadata(in); Assert.assertTrue(metadata.containsDirectory(ExifSubIFDDirectory.class)); Directory directory = metadata.getOrCreateDirectory(ExifSubIFDDirectory.class); Assert.assertEquals("80", directory.getString(ExifSubIFDDirectory.TAG_ISO_EQUIVALENT)); }
@Before public void setUp() throws Exception { File nikonJpeg = new File("Tests/com/drew/metadata/exif/nikonMakernoteType1.jpg"); Metadata metadata = JpegMetadataReader.readMetadata(nikonJpeg); _nikonDirectory = metadata.getDirectory(NikonType1MakernoteDirectory.class); _exifSubIFDDirectory = metadata.getDirectory(ExifSubIFDDirectory.class); _exifIFD0Directory = metadata.getDirectory(ExifIFD0Directory.class); _thumbDirectory = metadata.getDirectory(ExifThumbnailDirectory.class); }
private static Directory getMetaDirectory(File file) { try { Metadata metadata = JpegMetadataReader.readMetadata(file); return metadata.getDirectory(ExifDirectory.class); } catch (JpegProcessingException e) { e.printStackTrace(); } return null; }
// ---------------------------------------------------------------------------------------------------- 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_"; } }
// ---------------------------------------------------------------------------------------------------- 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 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); }
/* (non-Javadoc) * @see org.inbio.m3s.dao.multimedia.MetadataExtractorDAO#init(java.lang.String) */ public void init(String fileAddress) throws IllegalArgumentException { logger.info("using the fileAddress: '" + fileAddress + "'"); this.fileAddress = fileAddress; try { File jpegFile = new File(fileAddress); Metadata metadata = JpegMetadataReader.readMetadata(jpegFile); this.exifDirectory = metadata.getDirectory(ExifDirectory.class); } catch (JpegProcessingException e) { e.printStackTrace(); throw new IllegalArgumentException( "The fileAddress [" + fileAddress + "] doesn't exist. ", e.getCause()); } }
/** * 打印出单个图片的元信息 * * @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); }
/** * Performs the Exif data extraction, adding found values to the specified instance of <code> * Metadata</code>. */ public Metadata extract(Metadata metadata) { if (_data == null) { return metadata; } Directory directory = metadata.getDirectory(IptcDirectory.class); // find start of data int offset = 0; try { while (offset < _data.length - 1 && get32Bits(offset) != 0x1c02) { offset++; } } catch (MetadataException e) { directory.addError("Couldn't find start of Iptc data (invalid segment)"); return metadata; } // for each tag while (offset < _data.length) { // identifies start of a tag if (_data[offset] != 0x1c) { break; } // we need at least five bytes left to read a tag if ((offset + 5) >= _data.length) { break; } offset++; int directoryType; int tagType; int tagByteCount; try { directoryType = _data[offset++]; tagType = _data[offset++]; tagByteCount = get32Bits(offset); } catch (MetadataException e) { directory.addError("Iptc data segment ended mid-way through tag descriptor"); return metadata; } offset += 2; if ((offset + tagByteCount) > _data.length) { directory.addError("data for tag extends beyond end of iptc segment"); break; } processTag(directory, directoryType, tagType, offset, tagByteCount); offset += tagByteCount; } return metadata; }
private void extractMetadata(UploadItem item, Image image) { InputStream in = null; try { in = new FileInputStream(item.getFile()); Metadata metadata = JpegMetadataReader.readMetadata(in); Directory exifDirectory = metadata.getDirectory(ExifDirectory.class); Directory jpgDirectory = metadata.getDirectory(JpegDirectory.class); setupCameraModel(image, exifDirectory); setupDimensions(image, exifDirectory, jpgDirectory); setupCreatedDate(image, exifDirectory); } catch (Exception e) { addError(item, image, Constants.IMAGE_SAVING_ERROR); } finally { try { in.close(); } catch (IOException e) { addError(item, image, Constants.IMAGE_SAVING_ERROR); } } }
public ImageGeo(String filename) { try { error = false; File jpegFile = new File(filename); Metadata metadata = JpegMetadataReader.readMetadata(jpegFile); GpsDirectory gpsdir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class); Rational latpart[] = gpsdir.getRationalArray(GpsDirectory.TAG_GPS_LATITUDE); Rational lonpart[] = gpsdir.getRationalArray(GpsDirectory.TAG_GPS_LONGITUDE); String northing = gpsdir.getString(GpsDirectory.TAG_GPS_LATITUDE_REF); String easting = gpsdir.getString(GpsDirectory.TAG_GPS_LONGITUDE_REF); try { alt = gpsdir.getDouble(GpsDirectory.TAG_GPS_ALTITUDE); } catch (Exception ex) { } double latsign = 1.0d; if (northing.equalsIgnoreCase("S")) latsign = -1.0d; double lonsign = 1.0d; if (easting.equalsIgnoreCase("W")) lonsign = -1.0d; lat = (Math.abs(latpart[0].doubleValue()) + latpart[1].doubleValue() / 60.0d + latpart[2].doubleValue() / 3600.0d) * latsign; lon = (Math.abs(lonpart[0].doubleValue()) + lonpart[1].doubleValue() / 60.0d + lonpart[2].doubleValue() / 3600.0d) * lonsign; if (Double.isNaN(lat) || Double.isNaN(lon)) error = true; } catch (Exception ex) { error = true; } System.out.println(filename + ": (" + lat + ", " + lon + ")"); }
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); } }
/** * @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; }
/** * Tries to read the orientation data from the given image {@link Metadata}. Returns <code>null * </code> if not found or if an error occurs. */ @Nullable public static ImageOrientation getOrientation(@Nullable final Metadata metadata) { if (metadata != null) { final Directory exifIfd0Directory = metadata.getDirectory(ExifIFD0Directory.class); if (exifIfd0Directory != null) { try { return findById(exifIfd0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION)); } catch (Exception e) { LOG.info( "ImageOrientation.getOrientation(): Exception while trying to read the orientation data from the EXIF. Ignoring and just returning null"); } } } return null; }
/** * 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); }
/** * 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"); } } } }
/** * 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); }
private static void extractExif(ImageEntry e) { double deg; double min, sec; double lon, lat; Metadata metadata = null; Directory dir = null; try { metadata = JpegMetadataReader.readMetadata(e.getFile()); dir = metadata.getDirectory(GpsDirectory.class); } catch (CompoundException p) { e.setExifCoor(null); e.setPos(null); return; } try { // longitude Rational[] components = dir.getRationalArray(GpsDirectory.TAG_GPS_LONGITUDE); deg = components[0].doubleValue(); min = components[1].doubleValue(); sec = components[2].doubleValue(); if (Double.isNaN(deg) && Double.isNaN(min) && Double.isNaN(sec)) throw new IllegalArgumentException(); lon = (Double.isNaN(deg) ? 0 : deg + (Double.isNaN(min) ? 0 : (min / 60)) + (Double.isNaN(sec) ? 0 : (sec / 3600))); if (dir.getString(GpsDirectory.TAG_GPS_LONGITUDE_REF).charAt(0) == 'W') { lon = -lon; } // latitude components = dir.getRationalArray(GpsDirectory.TAG_GPS_LATITUDE); deg = components[0].doubleValue(); min = components[1].doubleValue(); sec = components[2].doubleValue(); if (Double.isNaN(deg) && Double.isNaN(min) && Double.isNaN(sec)) throw new IllegalArgumentException(); lat = (Double.isNaN(deg) ? 0 : deg + (Double.isNaN(min) ? 0 : (min / 60)) + (Double.isNaN(sec) ? 0 : (sec / 3600))); if (Double.isNaN(lat)) throw new IllegalArgumentException(); if (dir.getString(GpsDirectory.TAG_GPS_LATITUDE_REF).charAt(0) == 'S') { lat = -lat; } // Store values e.setExifCoor(new LatLon(lat, lon)); e.setPos(e.getExifCoor()); } catch (CompoundException p) { // Try to read lon/lat as double value (Nonstandard, created by some cameras -> #5220) try { Double longitude = dir.getDouble(GpsDirectory.TAG_GPS_LONGITUDE); Double latitude = dir.getDouble(GpsDirectory.TAG_GPS_LATITUDE); if (longitude == null || latitude == null) throw new CompoundException(""); // Store values e.setExifCoor(new LatLon(latitude, longitude)); e.setPos(e.getExifCoor()); } catch (CompoundException ex) { e.setExifCoor(null); e.setPos(null); } } catch (Exception ex) { // (other exceptions, e.g. #5271) System.err.println("Error when reading EXIF from file: " + ex); e.setExifCoor(null); e.setPos(null); } // compass direction value Rational direction = null; try { direction = dir.getRational(GpsDirectory.TAG_GPS_IMG_DIRECTION); if (direction != null) { e.setExifImgDir(direction.doubleValue()); } } catch (Exception ex) { // (CompoundException and other exceptions, e.g. #5271) // Do nothing } }
/** * 保持上传照片的图片方向不发生调整 * * @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); } }