使⽤com.sun.imageio.plugins.png.PNGMetadata读取图⽚的元数据所谓图⽚元数据,就是除了我们⾁眼看到的图⽚内容外,隐藏在这些内容背后的⼀些技术数据。
本⽂介绍如何使⽤Java代码将⼀张图⽚的隐藏信息读取出来。
⾸先不需要下载任何额外的Java库,⽤JDK⾃带的库就能⼯作。
import ByteArrayInputStream;
import File;
import FileInputStream;
import IOException;
import ImageIO;
import ImageReader;
import IIOMetadata;
import IIOMetadataNode;
import NamedNodeMap;
import Node;
import NodeList;
import PNGMetadata;
新建⼀个Java类,这个类的main⽅法也是⾮常直接的:
static public void main(String[] arg)throws IOException{
byte[] content =getContent("C:\Users\i042416\Desktop\test\clipboard1.png");
readCustomData(content);
}
⾸先把桌⾯上名叫clipboard1.png的图⽚⽂件的内容读到字节数组content中。
getContent⽅法的代码:
⼀张png图⽚的元数据,散布在下⾯这些节点⾥:StandardChromaNode()); StandardCompressionNode()); StandardDataNode()); StandardDimensionNode()); StandardDocumentNode()); StandardTextNode()); StandardTransparencyNode());通过printNode打印出来:
printNode⽅法的源代码:
打印出来的元数据:
如果⼤家想要复制粘贴,这是全部的源代码:package;
import ByteArrayInputStream;
import File;
import FileInputStream;
import IOException;
import ImageIO;
import ImageReader;
import IIOMetadata;
import IIOMetadataNode;
import NamedNodeMap;
import Node;
import NodeList;
import PNGMetadata;
public class pngTest {
static private byte[]getContent(String filePath)throws IOException {
File file =new File(filePath);
long fileSize = file.length();
图片下载站源码if(fileSize > Integer.MAX_VALUE){
System.out.println("file ");
return null;
}
FileInputStream fi =new FileInputStream(file);
byte[] buffer =new byte[(int) fileSize];
int offset =0;
int numRead =0;
while(offset < buffer.length
&&(numRead = fi.read(buffer, offset, buffer.length - offset))>=0){
offset += numRead;
}
if(offset != buffer.length){
fi.close();
throw new IOException("Could not completely read file "
+ Name());
}
fi.close();
return buffer;
}
static private void readCustomData(byte[] imageData)throws IOException{
ImageReader imageReader = ImageReadersByFormatName("png").next(); imageReader.ateImageInputStream(new ByteArrayInputStream(imageData)),true); IIOMetadata metadata = ImageMetadata(0);
PNGMetadata pngmeta =(PNGMetadata) metadata;
StandardChromaNode());
StandardCompressionNode());
StandardDataNode());
StandardDimensionNode());
StandardDocumentNode());
StandardTextNode());
StandardTransparencyNode());
}
static private void printNode(IIOMetadataNode metanode){
if(metanode ==null)
return;
NodeList childNodes = ChildNodes();
if( childNodes ==null)
return;
for(int i =0; i < Length(); i++){
Node node = childNodes.item(i);
NamedNodeMap attribute = Attributes();
if( attribute ==null)
continue;
int length = Length();
for(int j =0; j < length; j++){
Node each = attribute.item(j);
String value = NodeValue();
String name = NodeName();
System.out.println("Name: "+ name +" value: "+ value);
}
}
}
static public void main(String[] arg)throws IOException{
byte[] content =getContent("C:\Users\i042416\Desktop\test\clipboard1.png"); readCustomData(content);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。