Search code examples
javaimageswingfilesizeimageicon

Java Icon Image Maximum File Size


I am working on a chess game on Java. I have been importing images onto Eclipse and then assigning them to ImageIcons, and then subsequently assigning these ImageIcons onto buttons to form a grid.

At one point three out of my four bishop images were not being assigned to their respective buttons and so I looked at the file size and it turns out that the sizes of the three images that weren't being assigned were ~1,100KB, ~1,200KB, and ~40KB. The image that was being assigned to the button was around 25KB. I thought this was odd (especially since all four images are very similar) so I exported the three problematic images in a lower resolution (all under 30KB), and then re-imported them into Eclipse. When I ran my program again they were assigned to the right buttons and everything ran smoothly again.

The buttons that I am using are all 75 x 75 pixels, and the pixels were the same for each image (75 x 75), so I am confused why this happened. I looked for any questions relating to this, but I could not find any. If anyone could help explain why this could happen to me that would be very helpful so I can avoid this problem in the future.


Solution

  • I recommend using png for transparent images and icons, jpg for non-transparent images - and only if compression artifacts don't matter (lossless JPEG sadly isn't widely spread). bmp is one of the worst file formats out there if it comes to file size. As suggested by the others, load images in java with the ImageIO API:

    public class Program {
        public static void main(String[] args) {
            InputStream imageSource = Program.class.getResourceAsStream("bishop"); // may be a URL, File or ImageInputStream instead
            try {
                BufferedImage bishopImage = ImageIO.read(imageSource); // read image
                ImageIcon bishopIcon = new ImageIcon(bishopImage); // use adapter for Icon interface
                System.out.println(bishopIcon); // do something with it
            } catch (IOException e) {
                e.printStackTrace(); // read failed
            }
        }
    }