Resize a picture to fit a JLabel

后端 未结 8 567
不思量自难忘°
不思量自难忘° 2020-11-29 01:56

I\'m trying to make a picture fit a JLabel. I wish to reduce the picture dimensions to something more appropriate for my Swing JPanel.

I tried with setPreferredSiz

8条回答
  •  感动是毒
    2020-11-29 02:41

    public static void main(String s[]) 
      {
    
        BufferedImage image = null;
        try 
        {
            image = ImageIO.read(new File("your image path"));
    
        } catch (Exception e) 
        {
            e.printStackTrace();
        }
    
        ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
        jLabel1.setIcon(imageIcon);
    }
    
    
    private Image fitimage(Image img , int w , int h)
    {
        BufferedImage 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();
        return resizedimage;
    }
    

提交回复
热议问题