如何在不使用filechooser的情况下将jlabel中的图像图标转换为字节

时间:2015-02-02 06:49:47

标签: java jlabel imageicon

我刚接触java开发,我可以使用文件选择器将图像插入数据库,然后转换为字节,问题是我想将默认图像保存到数据库而不使用文件选择器。我设置标签通过属性的特定图像。我可以将我设置的默认图像转换为标签吗?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

是的,这是可能的。您需要将IconJLabel转换为BufferedImage,然后您可以通过ImageIO API将其传递给byte[]数组

Icon icon = null;
BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();

try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    try {
        ImageIO.write(img, "png", ios);
        // Set a flag to indicate that the write was successful
    } finally {
        ios.close();
    }
    byte[] bytes = baos.toByteArray();
} catch (IOException ex) {
    ex.printStackTrace();
}

答案 1 :(得分:0)

我的项目零件代码:

..........
BufferedImage bfi = getBufferedImage(iconToImage(my_Jlabel.getIcon()));                   
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageIO.write(bfi, "png", bs);
byte[] byteArray = bs.toByteArray();
pstmt.setBytes(17, byteArray);
.............

 public static BufferedImage getBufferedImage(Image img){
if (img instanceof BufferedImage)
{
   return (BufferedImage) img;
}


BufferedImage bimage = new BufferedImage(img.getWidth(null), 
                img.getHeight(null), BufferedImage.TYPE_INT_ARGB);


Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();

return bimage;
} 


static Image iconToImage(Icon icon) {    
if (icon instanceof ImageIcon) {
return ((ImageIcon)icon).getImage();
} 
else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge = 
    GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice gd = ge.getDefaultScreenDevice();
  GraphicsConfiguration gc = gd.getDefaultConfiguration();
  BufferedImage image = gc.createCompatibleImage(w, h);
  Graphics2D g = image.createGraphics();
  icon.paintIcon(null, g, 0, 0);
  g.dispose();
  return image;
}
}