How to convert JLabel.getIcon() to BufferedImage

大兔子大兔子 提交于 2021-01-28 01:35:03

问题


I have a JLabel that contains only an icon, and I can get the Icon with label1.getIcon(), but I can't figure out how to convert that Icon into a BufferedImage. Just FYI, I'm not talking about ImageIcon, only Icon. Also, I have seen the question at How to convert Icon from JLabel into BufferedImage?, but I can't seem to figure it out.

As always, any examples or explanation are much appreciated. Thanks!


回答1:


You may try this.

// Get the icon
Icon ico = label1.getIcon();
// Create a buffered image
BufferedImage bimg = new BufferedImage(ico.getIconWidth(), ico.getIconHeight(),
                                       BufferedImage.TYPE_INT_RGB);
// Create the graphics context
Graphics g = bimg.createGraphics();
// Now paint the icon
ico.paintIcon(null, g, 0, 0);
g.dispose();



回答2:


As JLabel.getIcon() returns a Icon so you want to convert the Icon to bufferedImage.I think you need to view this question.Here you can get the way through which you can convert a icon to BufferedImage



来源:https://stackoverflow.com/questions/14228433/how-to-convert-jlabel-geticon-to-bufferedimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!