Scale the ImageIcon automatically to label size

后端 未结 7 2052
梦如初夏
梦如初夏 2020-11-22 15:15

On my JFrame, I am using the following code to display an image on the Panel :

  ImageIcon img= new ImageIcon(\"res.png\");
  jLabel.setIcon(img);

7条回答
  •  我在风中等你
    2020-11-22 16:12

    private Image fitimage(Image img, int w, int h) {
        int width = img.getWidth(this);
        int height = img.getHeight(this);
        BufferedImage resizedimage;
    
        if (width > w && height > h) {
            resizedimage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = resizedimage.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(img, 0, 0, w, h, null);
            g2.dispose();
        } else {
            resizedimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = resizedimage.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(img, 0, 0, width, height, null);
            g2.dispose();
        }
        return resizedimage;
    }
    

提交回复
热议问题