Reputation: 7540
Is it possible to feed an array of image names into code which converts images to greyscale?
I am able to convert an image into greyscale by using this code:
public static void makeGrey() {
try{
//Read in original image.
BufferedImage image = ImageIO.read(new File("images\\012.jpg"));
//Obtain width and height of image.
double image_width = image.getWidth();
double image_height = image.getHeight();
BufferedImage bimg = null;
BufferedImage img = image;
//Draw the new image.
bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
//Save new greyscale (output) image.
String temp = "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
}
catch (Exception e){
System.out.println(e);
}
}
However, this code only works on a single file at a time and I would like to know how to go about getting it to work through all files located in the images
directory?
I have created an array which goes through the images
directory and stores the names of all of the files and I would like to know how to pass these filenames into my makeGrey()
method?
static File dir = new File("images");
static File imgList[] = dir.listFiles();
public static void listFiles(String imageName) {
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeGrey.makeGrey();
}
}
}
Thank you.
Upvotes: 1
Views: 442
Reputation: 13918
Your makeGray()
method should look like this:
public static void makeGrey(File image) {
try{
//Read in original image.
BufferedImage inputImage = ImageIO.read(image);
...
...
//Save new greyscale (output) image. (Or you'll rewrite same image all the time...)
File fi = new File("images\\inverted_" + image.getName()
...
...
and other part of the code should call it like this:
static File dir = new File("images");
static File imgList[] = dir.listFiles();
public static void listFiles(String imageName) {
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeGrey.makeGrey(img);
}
}
}
Upvotes: 2