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