Search code examples
javaphoto-gallery

The best way to load pictures for photo gallery


I want to make some kind of a book(or some kind of a photo gallery) using jpg files of a scanned book. the user gives the number of the page that he wants to go to , and clicks on the button to see the page . I need to know what is the best way to load the pictures. i'm thinking of doing this for each page:

private ImageIcon image1= new ImageIcon ("1.jpg");
private ImageIcon image2 = new ImageIcon ("2.jpg");
....

and then put the pictures in an array and so on ... but i got over 500 pictures and it is tedious to load pages like that . so is there any other way?


Solution

  • Well, I can say the best way would be lazy loading plus pre-caching. Lazy loading means you load the image only when the user needs it. For example:

    img = 56; // suppose the user want to see page 56
    if(images[img] != null) { // images is an array with the images
        images[img] = new ImageIcon (img + ".jpg");
    }
    

    Besides, you can guest that when the user see a page they will see the next ones (pre-caching). So you can also load the following X pages.

    PRELOAD = 10; // number of pages to preload
    img = 56;
    for(int i = 0; i < PRELOAD; i++) {
      if(images[img+i] != null) {
        images[img+i] = new ImageIcon ((img + i) + ".jpg");
      }
    }
    

    Besides, it's you may think that in the beginning the user will always look at the firsts pages. So you can pre-load the first X pages in the start of your program.