如何在不使用文件选择器的情况下将jlabel中的图像图标转换为字节

How to convert image icon in jlabel to byte without using filechooser

我刚开始 java 开发,我可以使用文件选择器将图像插入数据库,然后转换为字节,问题是我想在不使用文件的情况下将默认图像保存到数据库中 chooser.I 通过properties.Can 设置带有特定图像的标签我将我设置的默认图像转换为标签?

任何帮助将不胜感激。

是的,这是可能的。您需要将 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();
}

我的项目部分代码:

..........
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;
}
}