Search code examples
javajlabelimageicon

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


I'm just new at java development, i can insert image into database by using file chooser and then convert to byte,the problem is i want to save a default image into database without using file chooser.I set the label with a specific image through properties.Can i convert the default image i set to label?

any help will be appreciated.


Solution

  • Yes, it's possible. You need to convert the Icon from the JLabel to BufferedImage, from there you can simply pass it through the ImageIO API to get a byte[] array

    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();
    }