0

This is what i have tried to scale image using getScaledInstance(). But its not scaling the image. Can anybody correct this code?

BufferedImage image = ImageIO.read(new File("img.jpg"));
JLabel picLabel = new JLabel(new ImageIcon(image));
image=(BufferedImage)image.getScaledInstance(50,50, Image. SCALE_SMOOTH);
add(picLabel);
Barett
  • 5,826
  • 6
  • 51
  • 55
Ani
  • 177
  • 2
  • 3
  • 14
  • 3
    Possible duplicate of http://stackoverflow.com/questions/7252983/resizing-image-java-getscaledinstance – kiheru Jul 17 '13 at 15:34

2 Answers2

4

Creating a new image does not update the ImageIcon. Change the order of your code:

//BufferedImage image = ImageIO.read(new File("img.jpg"));
//JLabel picLabel = new JLabel(new ImageIcon(image));
Image image = ImageIO.read(new File("img.jpg"));
image=image.getScaledInstance(50,50, Image. SCALE_SMOOTH);
JLabel picLabel = new JLabel(new ImageIcon(image));
add(picLabel);

Edit: the original code you posted doesn't even execute. You can't cast the scaled image to a BufferedImage. I updated the code to solve the execution problem.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

I done this and now its working fine. :)

    BufferedImage image = ImageIO.read(new File("img.jpg"));
    BufferedImage img = new BufferedImage(200,150,BufferedImage.TYPE_INT_RGB);
    img.getGraphics().drawImage(image,0,0,200,150,null);

    JLabel label = new JLabel(new ImageIcon(img));
    add(label);
Ani
  • 177
  • 2
  • 3
  • 14
  • the problem with your original code is that it doesn't even execute because you can't cast the scaled image to a BufferedImage. I update my original answer. – camickr Jul 17 '13 at 17:29