What causes poor image quality in Java JLabel icons?

后端 未结 3 1478
渐次进展
渐次进展 2021-01-17 22:06

Java JLabel icons are displaying with distorted pixels in JFrame. This is happening consistently with different png images (all 32x32). I am not sc

3条回答
  •  再見小時候
    2021-01-17 22:35

    First option: Instead of using ImageIcon, you can try to create your own icon class drawing the Image using graphics.drawImage(x,y,width,height,null) controlling rendering quality (https://docs.oracle.com/javase/tutorial/2d/advanced/quality.html)

    an example would be something like this:

    public class Icon32 extends ImageIcon {
        public Icon32(String f) {
          super(f);
    
          BufferedImage i= new BufferedImage(32, 32, 
               BufferedImage.TYPE_INT_RGB);
    
    
          Graphics2D g2d = (Graphics2D) i.getGraphics();
                    g2d.setRenderingHint(
                        RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    
                    g2d.setRenderingHint(
                        RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    
          g2d.drawImage(getImage(), 0, 0, 32, 32, null);
          setImage(i);
        }
    
        public int getIconHeight() {
          return 32;
        }
    
        public int getIconWidth() {
          return 32;
        }
    
        public void paintIcon(Component c, Graphics g, int x, int y) {
          g.drawImage(getImage(), x, y, c);
        }
      }
    

    where the method:

    getImage()
    

    is loading your image/icon...

    Second option: if you are not happy with the result you can try to use this library: https://github.com/mortennobel/java-image-scaling it claims to provides better image scaling options than the Java runtime provides.

提交回复
热议问题