-1

I've been trying to get an image from a JLabel icon and then convert that image to bytes before inserting it to database. I've done something like that but when I get the bytes from database and set it back to the JLabel as Icon, its just black. Any help? This is my code.

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);
    }
Emperor
  • 81
  • 1
  • 9
  • 1
    How are you storing it the database? How are you reading it from the database? How are you constituting the image to a `ImageIcon`? [That's one possible example](https://stackoverflow.com/questions/20752432/convert-bufferedinputstream-into-image/20753089#20753089) – MadProgrammer Aug 23 '18 at 08:56
  • 1
    The `image` object you're creating never receives any data from the icon aside from the width and height – Jeroen Steenbeeke Aug 23 '18 at 08:58
  • You might want to look at [Converting an ImageIcon to a BufferedImage](https://stackoverflow.com/questions/15053214/converting-an-imageicon-to-a-bufferedimage) – MadProgrammer Aug 23 '18 at 09:00
  • I'm storing it as blob in my MySQL database using pst.setBytes(); and reading it as byte[] f2 = rs.getBytes("passportdb"); ImageIcon ff = new ImageIcon(f2); Image img = ff.getImage(); – Emperor Aug 23 '18 at 09:00
  • Jeroen what do you suggest I do? – Emperor Aug 23 '18 at 09:14
  • I suggest using ImageIcon's `getImage` method and see if you can convert that to the type ImageIO uses – Jeroen Steenbeeke Aug 23 '18 at 10:11

1 Answers1

0

Thanks MadProgrammer, your link helped me. Its working now. This is my code

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);
    }
Emperor
  • 81
  • 1
  • 9