Search code examples
javapngzxing

zxing - export PNG barcode with encoded value


Using zxing, I managed to save a Code39 barcode as PNG but it does display only the bars, no numbers. How could I have the barcode and number in a single PNG?

KI


Solution

  • You cannot add the numbers using zxing. You could do something like adding the text yourself to the image, but this might not work flawlessly in all cases without fiddling.

    public static void main(String[] args) throws Exception {
        final BufferedImage image = ...
    
        Graphics g = image.getGraphics();
        g.setFont(g.getFont().deriveFont(20f)); // select compatible font
        g.drawString("numbers", 100, 100); // center on your image using image size
        g.dispose();
    
        ImageIO.write(image, "png", new File("barcode.png"));
    }
    

    Alternatively, you could organize all this in a JPanel and then render the panel to image. This would allow you to benefit from layout orientations and fittings. Using something like this.