我一直在尝试从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);
}
答案 0 :(得分: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);
}