Search code examples
javaimageresizejlabelautoresize

Re sizing an image on a jLabel


I trying to re size an image on a jLabel in java, the snippet of the code which is not working is given below:

ImageIcon imgThisImg = new ImageIcon(rs.getString("PictureURL"));
Image image=null;
image=jLabel2.createImage(120, 50);
ImageIcon imi=new ImageIcon(image);
jLabel2.setIcon(imi);

When i run it i get nothing on my jlabel. In fact if i run the code below it works fine. The thing is that i want a scaled down image:

ImageIcon imgThisImg = new ImageIcon(rs.getString("PictureURL"));
jLabel2.setIcon(imgThisImg);                          

I cant find where i am wrong. Please suggest me any ideas how should i go about it.

Thanks


Solution

  • Please see below a better solution for re-scaling an image. In the code below, newImage is the rescaled image.

    BufferedImage image = ImageIO.read(imageFile);
    BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType());
    Graphics2D g2 = newImage.createGraphics();
    g2.drawImage(image, 0, 0, newWidth, newHeight, null);
    g2.dispose();