Search code examples
javaqr-codezxing

how to add text below QR code using com.google.zxing libraby in JAVA


I have generated QR code using com.google.zxing this library. QRCode generations work fine but I want to display Data of QRcode below QRcode.

I want to generate QR code like attached below.

enter image description here

Here is my code.

QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        byte[] pngData = pngOutputStream.toByteArray();

Solution

  • Here I Generated QR Code file and took in memory and then used Graphics Lib. Using this Library could add Text to that Memory and saved it again.

    public static void main(String[] args) {        
       try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode("Hello world", BarcodeFormat.QR_CODE, 300, 300);
            Path path = FileSystems.getDefault().getPath("test.png");
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);     
            
            
                      
           final BufferedImage image = ImageIO.read(new File(path.toString()));
           JFrame frame = new JFrame();
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           Graphics g = image.getGraphics();
           g.setFont(g.getFont().deriveFont(22f));
           Color textColor = Color.BLACK;
           g.setColor(textColor);
           g.drawString("Hello world", 15, 300);
           g.dispose();
    
           ImageIO.write(image, "png", new File("test45.png"));
            
                       
        } catch (WriterException | IOException ex) {
            
        }  
    }