chinedu obiakara
chinedu obiakara

Reputation: 15

How to scan an image folder and add them to an image array

I am working on a project and one of the requirements is to scan a folder containing different Images. I need to find a way to scan the folder and add each image to an array of Images. Here is what I want to do

public class ImageScan {
   private ArrayList<Image> images = new ArrayList<>(); 

   public void loadImages() {

   ArrayList<Image> image_Array = new ArrayList<>();

   File file = new File("data/images");         
   BufferedImage image = ImageIO.read(file);

      while(image.hasNextImage()) {//hasnextImage() is  not a valid method, 
      //just to express my idea.

         Image image = //save read Image to an image instance
         //here all I want to do is add each image I obtain into an 
         //arrayList of images      

         image_Array.add(image);        
      }//end of while       

   this.setImages(image_Array);// i set image_Array using getter method 
   }//end of loadData method

}//end of class

Upvotes: 0

Views: 545

Answers (1)

JB Programming
JB Programming

Reputation: 56

Okay here is what I created:

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

public class ImageScan {

    private List<Image> images = new ArrayList<Image>();

    public void loadImages() {

        List<Image> imageArray = new ArrayList<Image>();

        File file = new File("data/images");

        File[] imageFiles = file.listFiles(); // This gets all of the files inside 
'file', if 'file' is a folder
        for (File f : imageFiles) {
            try {
                BufferedImage image = ImageIO.read(f);
                imageArray.add(image);
            } catch (Exception e) {
                // This makes sure only the images in the folder are used, not any 
file.
            }
        }

        this.setImages(imageArray);
    }

    public void setImages(List<Image> imageArray) {
        images = imageArray;
    }

    public List<Image> getImages() {
        return images;
    }

}

Upvotes: 1

Related Questions