当前位置: 动力学知识库 > 问答 > 编程问答 >

Error in resizing Image with the width of the label Java 8.0

问题描述:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: