Resize a picture to fit a JLabel

后端 未结 8 525
不思量自难忘°
不思量自难忘° 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;
    }
    
    0 讨论(0)
  • 2020-11-29 02:46

    Or u can do it this way. The function u put the below 6 lines will throw an IOException. And will take your JLabel as a parameter.

    BufferedImage bi=new BufferedImage(label.width(),label.height(),BufferedImage.TYPE_INT_RGB);
    
    Graphics2D g=bi.createGraphics();
    
    Image img=ImageIO.read(new File("path of your image"));
    
    g.drawImage(img, 0, 0, label.width(), label.height(), null);
    
    g.dispose();
    
    return bi;
    
    0 讨论(0)
提交回复
热议问题