简体   繁体   中英

Java - Apply Function to All Files in Given Directory

I would like to know if it is possible to apply a function to all files in a directory using Java?

More specifically, I am looking to read in all images in a folder, convert them to binary (two colours/black and white), and then save the binary image as a new image in another directory (probably directory\\binary , for example).

Something like this:

for(all images in folder)
    read in image
    make(binaryImg)
    saveNewImage
endFor

I have 300 images so was hoping that there is a way to do this?

Many thanks.

This should be relatively easy to do, and there are lots of posts here which deal with many of the parts of this program. For example, check out these previous questions:

Program to get all files within a directory in Java

Taking a picture as input, Make grey scale and & then outputting

There should be more than enough information there for you to make a start!

You can do it this way:

File dir = new File("/dir/");
for(File f : dir.listFiles())
  processImage(f);

Of course, since you have many files, you can create a Runnable for every file and pass them to an ExecutorService to process in multiple threads:

public static void main(String... args){

    ExecutorService pool = Executors.newFixedThreadPool(4); //nbr of active threads

    File dir = new File("/dir/");
    for(File f : dir.listFiles())
    pool.submit(new Runnable() {
         public void run(){
             processImage(f);
        }
    } 
}

Yes, it's possible. Take a look at java.io.File and try searching for topics about working with files in Java for information about how to go about accessing a directory and obtaining a list of the files it contains.

If you're looking for somebody to write the code for you, that's unlikely to happen.

The only "better way" I can think of is to use a multi threaded design here. Every 100 images for example all should be processed in a separate Thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM