利用metadata-extractor定向获取图片拍摄时间以及宽高

端木鹏
2023-12-01
  •  首先maven导包

<dependency>
      <groupId>com.drewnoakes</groupId>
      <artifactId>metadata-extractor</artifactId>
      <version>2.10.0</version>
</dependency>
  • 使用 

public static Map<String, Object> getImgInfo(InputStream is) throws ImageProcessingException, IOException {

		Map<String, Object> map = new HashMap<>();
		Date fileModifiedDate = null;
		Date dateTime = null;
		Integer imageWidth = null;
		Integer imageHeight = null;

		Metadata metadata = ImageMetadataReader.readMetadata(is);
		Iterable<Directory> directories = metadata.getDirectories();
		for (Directory directory : directories) {
			//获取图片最后修改时间
			if (directory instanceof FileMetadataDirectory) {
				fileModifiedDate = directory.getDate(FileMetadataDirectory.TAG_FILE_MODIFIED_DATE);
			}
			//获取图片的Exif拍摄时间
			if (directory instanceof ExifIFD0Directory) {
				dateTime = directory.getDate(ExifDirectoryBase.TAG_DATETIME);
			}

			//获取图片的长、宽
			//jpeg
			if (directory instanceof JpegDirectory) {
				imageWidth = directory.getInteger(JpegDirectory.TAG_IMAGE_WIDTH);
				imageHeight = directory.getInteger(JpegDirectory.TAG_IMAGE_HEIGHT);
			}
			//png
			if (directory instanceof PngDirectory) {
				PngDirectory pngDirectory = (PngDirectory) directory;
				PngChunkType pngChunkType = pngDirectory.getPngChunkType();
				if (pngChunkType.equals(PngChunkType.IHDR)) {
					imageWidth = directory.getInteger(PngDirectory.TAG_IMAGE_WIDTH);
					imageHeight = directory.getInteger(PngDirectory.TAG_IMAGE_HEIGHT);
				}
			}
			//gif
			if (directory instanceof GifHeaderDirectory) {
				imageWidth = directory.getInteger(GifHeaderDirectory.TAG_IMAGE_WIDTH);
				imageHeight = directory.getInteger(GifHeaderDirectory.TAG_IMAGE_HEIGHT);
			}
		}
		if (dateTime == null) {
			map.put("shootTime", dateTime);
		} else {
			map.put("shootTime", fileModifiedDate);
		}
		map.put("imageWidth", imageWidth);
		map.put("imageHeight", imageHeight);
		return map;
	}

 

 类似资料: