Scale the ImageIcon automatically to label size

后端 未结 7 1892
梦如初夏
梦如初夏 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:01

    Try this function:

    public static BufferedImage resize(BufferedImage image, int width, int height) {
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
        Graphics2D g2d = (Graphics2D) bi.createGraphics();
        g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g2d.drawImage(image, 0, 0, width, height, null);
        g2d.dispose();
        return bi;
    }
    
    BufferedImage image1=ImageIO.read(url.openStream());
         BufferedImage resizedImage=resize(image,100,100);
         System.out.println("Load image into frame...");
          icon=new ImageIcon(resizedImage);
    

提交回复
热议问题