-2

Hi Guys I'm having issue in my Image, I just want to resize the image w/ my label. By using the filechooser. Here is the code below.

  try {

                File file = jfc.getSelectedFile();
                java.net.URL url = file.toURL();

                BufferedImage imageBuf = null;
                BufferedImage imageSize = null;


                try {
                    imageBuf = ImageIO.read(url);
                    imageSize = (BufferedImage) imageBuf.getScaledInstance(jlbl_image.getWidth(), jlbl_image.getHeight(),Image.SCALE_SMOOTH);

                    ImageIcon img;
                    img = new ImageIcon(imageSize);
                    jlbl_image.setIcon(img);

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

Here is the error code when I load the image from fileChooser.

sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
kornben
  • 45
  • 1
  • 5

1 Answers1

0

The error message is telling you exactly what the problem is: your image is not a BufferedImage, and so it shouldn't be treated as one. Your assumption is incorrect, however. It's not a that the image loaded from the JFileChooser isn't a BufferedImage, rather it's the scaled image returned from the .getScaledInstance(...) that isn't. So instead cast it to the interface type, Image, and you should be able to use it.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • ...or rather, just change the type of `imageSize` to `Image`, do no casting at all, everybody wins. ;-) – Harald K Dec 15 '16 at 14:00