How to resize an image in a JPanel?

1

Good morning friends, is my first question on this website, I would like you to help me a little with this code ...

This is the code I am using, it returns the image with the initial dimensions of the jpanel; what I want is that by maximizing the window (when resizing the panel), the image is resized obtaining the new panel size.

Thanks for your help.

public Panel(JPanel jPanel){
    this.x = jPanel.getWidth();
    this.y= jPanel.getHeight();
    this.setSize(x, y);
}
@Override
public void paint(Graphics g){
    ImageIcon img = new ImageIcon(getClass().getResource("/iconos/fondo.jpg"));
    g.drawImage(img.getImage(), 0, 0, x, y, null);
}
    
asked by Gerardo Suárez 11.11.2017 в 18:10
source

1 answer

1

You can use this code and then convert it to ImageIcon

 public BufferedImage redimensionar_imagenes(InputStream imagen, int x, int y){
   BufferedImage bi=null;

    try {

        //se obtiene la imagen original
        BufferedImage decodificado = ImageIO.read(imagen);
        ImageIcon pic = new ImageIcon(decodificado);


        //se crea la nueva imagen con las dimensiones de interes
        bi = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(pic.getImage().getScaledInstance(x, y, Image.SCALE_FAST),0,0, null);
        g2.dispose();

        imagen.close();

    } catch (IOException ex) {
        Logger.getLogger(Procesamiento.class.getName()).log(Level.SEVERE, null, ex);
    }




return bi;
}
    
answered by 30.11.2017 в 00:30