0

I'm using a library called Image4j to load an ico file, choose one of the images from the list, scale it (if necessary) and put it in a JLabel as an ImageIcon.

The library has a method read(File icoFile) which returns a List<BufferedImage> , a list of all the images contained within the ico file.

What I want to be able to do is quickly choose the image from the list that is the closest fit for the size of the label. Both the labels and the ico images will be square.

I've come up with the most naive way, but I suspect there's a faster one. I'd settle for this one, but my program will be doing this routine a lot so I want this part to be as efficient as possible.

public class IconUtil() {

    private final List<BufferedImage> list;

    public IconUtil(List<BufferedImage> list) {
        this.list = list;
    }

    public BufferedImage getBestFit(int sizeToFit) {
        int indexOfBestFit = 0; // assume it's the first image
        int bestMargin = Math.abs(list.get(0).getWidth() - sizeToFit);
        int margin;

        for(int i = 1; i < list.size(); i++) {
            margin = Math.abs(list.get(i).getWidth() - sizeToFit);

            if(margin < bestMargin) {
                bestMargin = margin;
                indexOfBestFit = i;
            }
        }

        return list[indexOfBestFit];
    }

}

The choice to compare the images by their width was arbitrary because they're all square.

Also, as the main reason for picking the best fit is to try and maintain the quality of the images, should this method discard any images which are smaller than the target size? If so, how would that change the algorithm?

I have little experience with re-scaling images in Java. Is it even necessary to find the closest match in size? Maybe there are ways to re-scale without losing much quality even if the original is much bigger?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Dziugas
  • 1,500
  • 1
  • 12
  • 28
  • Scaling down shouldn't result in a loss of quality. When scaling up as the image gets bigger the image will distort because the information for a high resolution image is simply not there. The key is to find a middle ground of file size and image quality/scalability. Depending on your needs, you may also be able to use an SVG which would eliminate scaling issues completely. – MeetTitan Feb 20 '15 at 23:00
  • So all that is necessary is it pick any image that is bigger than the JLabel I intend to put it into? – Dziugas Feb 20 '15 at 23:01
  • 1
    Yes, unless it is ridiculously larger and you're scaling it by an ungodly amount, it should be pretty efficient and the quality will be there. – MeetTitan Feb 20 '15 at 23:02
  • 1
    Google Scalable Vector Graphics and see if you can incorporate them into your project, as they're (almost) always smaller (file-size wise), and always scale (up AND down) correctly. – MeetTitan Feb 20 '15 at 23:06

0 Answers0