使用Java从单个文件中读取图像元数据

时间:2013-04-20 02:19:07

标签: java image metadata

我想从单个文件中读取图像元数据。 我尝试了以下代码:

http://johnbokma.com/java/obtaining-image-metadata.html

当我运行它时,我得到build successful但没有任何反应。

public class Metadata {

    public static void main(String[] args) {
        Metadata meta = new Metadata();
        int length = args.length;
        for ( int i = 0; i < length; i++ )
        meta.readAndDisplayMetadata( args[i] );
    }

    void readAndDisplayMetadata( String fileName ) {
        try {

            File file = new File( fileName );
            ImageInputStream iis = ImageIO.createImageInputStream(file);
            Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);

            if (readers.hasNext()) {

                // pick the first available ImageReader
                ImageReader reader = readers.next();

                // attach source to the reader
                reader.setInput(iis, true);

                // read metadata of first image
                IIOMetadata metadata = reader.getImageMetadata(0);

                String[] names = metadata.getMetadataFormatNames();
                int length = names.length;
                for (int i = 0; i < length; i++) {
                    System.out.println( "Format name: " + names[ i ] );
                    displayMetadata(metadata.getAsTree(names[i]));
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}

请帮助:)

1 个答案:

答案 0 :(得分:1)

您尚未正确指定文件的路径。下面的更改应该表明这一点!

public static void main(String[] args) {
    Metadata meta = new Metadata();
    int length = args.length;
    for ( int i = 0; i < length; i++ ) {
        if (new File(args[i]).exists()) {
            meta.readAndDisplayMetadata( args[i] );
        } else {
            System.out.println("cannot find file: " + args[i]);
        }
    }
}

编辑 - 更简单的代码示例

我们现在静态地定义要使用的文件。

public static void main(String[] args) {
    Metadata meta = new Metadata();
    String filename = "C:\\Users\\luckheart\\Pictures\\Sample Pictures\\Koala.jpg";
    if (new File(filename).exists()) {
        meta.readAndDisplayMetadata(filename);
    } else {
        System.out.println("cannot find file: " + filename);
    }
}