Read Image Metadata from single file with Java

女生的网名这么多〃 提交于 2019-12-30 07:51:31

问题


I want to read image metadata from a single file. I tried the following code:

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

When I run it, I get build successful but nothing happens.

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();
        }
    }

}

Please help :)


回答1:


You haven't specified the path to the file correctly. The change below should indicate this!

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]);
        }
    }
}

EDIT - Simpler code example

We are now statically defining which file to use.

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);
    }
}


来源:https://stackoverflow.com/questions/16115851/read-image-metadata-from-single-file-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!