将 JLabel 图标转换为 Java 中的字节

Convert a JLabel Icon to bytes in Java

我一直在尝试从 JLabel 图标获取图像,然后将该图像转换为字节,然后再将其插入数据库。 我做过类似的事情,但是当我从数据库中获取字节并将其作为 Icon 设置回 JLabel 时,它只是黑色的。有什么帮助吗? 这是我的代码。

try {
      Icon icons = passpo.getIcon();
      BufferedImage image = new BufferedImage(icons.getIconWidth(),
        icons.getIconHeight(),BufferedImage.TYPE_INT_RGB);
     ByteArrayOutputStream b =new ByteArrayOutputStream();
     ImageIO.write(image, "jpg", b );
     byte[] imageInByte = b.toByteArray();
       byte[] photos  = imageInByte;
    } catch (IOException d) {
        JOptionPane.showMessageDialog(this, d);
    }

感谢 MadProgrammer,您的 link 帮助了我。它现在工作。这是我的代码

try {
        Icon icons = passpo.getIcon();
        BufferedImage bi = new BufferedImage(icons.getIconWidth(), icons.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        icons.paintIcon(null, g, 0, 0);
        g.setColor(Color.WHITE);
        g.drawString(passpo.getText(), 10, 20);
        g.dispose();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", os);
        InputStream fis = new ByteArrayInputStream(os.toByteArray());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum);
            System.out.println("read " + readNum + " bytes,");
            }
         byte[] bytes = bos.toByteArray();
        photo = bytes;
    } catch (IOException d) {
        JOptionPane.showMessageDialog(rootPane, d);
    }