Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

Image Metadata for a specified directory in Java

Here I have code for displaying metadata for 1 file. I wanted to know how can I use to display metadata for a specified directory?

import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.imageio.metadata.*;
import java.util.Scanner;

public class Metadata{

    public static void main(String[] args) {
        Metadata meta = new Metadata();


        if (new File("./images/test.jpg").exists()) {
            System.out.println("Can find " + "test.jpg file");
            meta.readAndDisplayMetadata("test.jpg");
        } else {
            System.out.println("cannot find file: " + "test.jpg");
        }


    }


    void readAndDisplayMetadata(String fileName ) {//or 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();
        }
    }

    void displayMetadata(Node root) {
        displayMetadata(root, 0);
    }

    void indent(int level) {
        for (int i = 0; i < level; i++)
            System.out.print("    ");
    }

    void displayMetadata(Node node, int level) {
        // print open tag of element
        indent(level);
        System.out.print("<" + node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {

            // print attribute values
            int length = map.getLength();
            for (int i = 0; i < length; i++) {
                Node attr = map.item(i);
                System.out.print(" " + attr.getNodeName() +
                                 "="" + attr.getNodeValue() + """);
            }
        }

        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 children recursively
            displayMetadata(child, level + 1);
            child = child.getNextSibling();
        }

        // print close tag of element
        indent(level);
        System.out.println("</" + node.getNodeName() + ">");
    }
} 

I have used DirectoryPath but sadly ImageInputStream has no interface for directories.

Are there any libraries or frameworks that are available that can automatically give image metadata for a directory as JSON?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given that you already have code to displaying metadata for a single file, it's trivial to modify it to support multiple files.

All you need is the isDirectory() and listFiles() methods of File (or, if you are on Java 8+, you can use the Files.list(Path) method, for lazy iteration*).

If your input file is a directory, list each file and recurse:

public class Metadata {

    public static void main(String[] args) {
        Metadata meta = new Metadata();

        File file = new File(args[0]);

        if (file.exists()) {
            System.out.println("Can find " + file);
            meta.readAndDisplayMetadata(file);
        }
        else {
            System.out.println("cannot find file: " + file);
        }
    }

    void readAndDisplayMetadata(File file)  {
        // If you *don't* want recursive behavior, 
        // move this block "outside" or to a separate method 
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                readAndDisplayMetadata(f);
            }
        }

        // Rest of method as is...
    }
}

*) The below is better, if you can use it, as the above can run out of memory if you have many files in the directory.

void readAndDisplayMetadata(File file) throws IOException {
    Path path = file.toPath();
    if (Files.isDirectory(path /* optional, handle symbolic links */)) {
        Files.list(path)
             .forEach(p -> readAndDisplayMetadata(p.toFile()));
    }

    // Rest of method as is...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...