简体   繁体   中英

Convert Multiple Images to Grayscale using Java

My program is reading all the files but converts last file to b/w and change all the present images in the folder to that converted image. what should i do?

//read-image
    try{
      f=new File("path");
      File[] files=f.listFiles();
      for (File file:files){
          ImageInputStream is = ImageIO.createImageInputStream(file);
          img= ImageIO.read(is);
        }
      System.out.println("Reading Complete.");
    }
      catch(IOException e){
        System.out.println("Error"+e);
      }

            //write-image
      try{
        f= new File("path");
        File[] files=f.listFiles();
      for (File file:files){
        ImageOutputStream os = ImageIO.createImageOutputStream(file);
        ImageIO.write(img,"jpeg",os);
        System.out.println("Writing Complete");
        os.flush();
        os.close();
    }
      }
      catch(IOException e){
        System.out.println("Error"+e);
      }

Your code reads all files, but retains only one img object (the last one). You can solve this by merging both parts of it — read, edit, and write:

try {
    f = new File("path");
    File[] files = f.listFiles();
    for (File file : files){
        Image img;
        try (ImageInputStream is = ImageIO.createImageInputStream(file)) {
            img = ImageIO.read(is);
        }
        Image imgGrayscale = makeImageGrayscale(img);
        try (ImageOutputStream os = ImageIO.createImageOutputStream(file)) {
            ImageIO.write(img, "jpeg", os);
        }
    }
} catch(IOException e){
    System.out.println("Error"+e);
}

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