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

问题描述 投票:-1回答:1

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

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);
    }
java icons byte jlabel
1个回答
0
投票

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

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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.