java 读取 tiff文件dpi
时间: 2024-06-13 14:07:29 浏览: 169
Java读取TIFF文件
4星 · 用户满意度95%
以下是Java读取TIFF文件DPI的示例代码:
```java
import javax.imageio.ImageIO;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.tiff.TIFFImageReadParam;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ReadTiffDpi {
public static void main(String[] args) throws IOException {
File file = new File("input.tiff");
ImageInputStream iis = ImageIO.createImageInputStream(file);
TIFFImageReadParam param = new TIFFImageReadParam();
param.setDecodeTiled(false);
ImageIO.setUseCache(false);
BufferedImage image = ImageIO.read(iis);
IIOMetadata metadata = ImageIO.getImageReadersByFormatName("TIFF").next().getImageMetadata(0);
String[] names = metadata.getMetadataFormatNames();
for (String name : names) {
System.out.println("Format name: " + name); displayMetadata(metadata.getAsTree(name));
}
}
private static void displayMetadata(Node root) {
displayMetadata(root, 0);
}
private static void indent(int level) {
for (int i = 0; i < level; i++)
System.out.print(" ");
}
private static void displayMetadata(Node node, int level) {
// Print node name and attribute values
indent(level);
System.out.print("<" + node.getNodeName());
NamedNodeMap map = node.getAttributes();
if (map != null) {
for (int i = 0; i < map.getLength(); i++) {
Node attr = map.item(i);
System.out.print(" " + attr.getNodeName() +
"=\"" + attr.getNodeValue() + "\"");
}
}
// Print children recursively
Node child = node.getFirstChild();
if (child == null) {
// No children, so close element and return
System.out.println("/>");
return;
}
// Children, so close current tag
System.out.println(">");
while (child != null) {
// Print child recursively
displayMetadata(child, level + 1);
child = child.getNextSibling();
}
// Print closing tag
indent(level);
System.out.println("</" + node.getNodeName() + ">");
}
}
```
该代码使用Java的ImageIO库读取TIFF文件,并使用TIFFImageReadParam类设置解码参数。然后,它使用ImageIO.getImageReadersByFormatName("TIFF").next().getImageMetadata(0)方法获取元数据,并使用displayMetadata()方法显示元数据。其中,DPI信息可以在元数据中找到。
阅读全文