QR Code encoding using zxing to encode url data

270 views Asked by At

I want to embed some raw text as well as a url inside a qr code. for example data can be : ABCD http://www.example.com XYZ now on scanning http://www.example.com should be popped up and remaining data should be kept intact. means i will encode (ABCD http://www.example.com XYZ) inside my qr code but i want (http://www.example.com) to be popped up.

I have tried it using zxing but on scanning extire string gets displayed

    public static void main(String[] args) {
    // Define the data, including a properly formatted URL
    String data = "ABCD https://www.google.com fgh";

    // Define QR code properties
    int width = 300;
    int height = 300;
    String fileType = "png"; // or "jpg", "gif", etc.

    // Create hints for QR code generation
    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hints.put(EncodeHintType.MARGIN, 1);

    try {
        // Generate QR code
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height, hints);

        // Create a BufferedImage from the BitMatrix
        BufferedImage qrImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                qrImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        // Save the QR code to a file
        File qrFile = new File("clickable_url_qrcode." + fileType);
        ImageIO.write(qrImage, fileType, qrFile);

        System.out.println("Clickable URL QR code generated successfully!");

    } catch (Exception e) {
        System.err.println("Error generating QR code: " + e.getMessage());
    }
}

Output: ABCD https://www.google.com fgh on scanning qr

I have to use this format as because this is just an example but i am using emvco specification which is correctly specified and there link is preceeded and succeeded by space

1

There are 1 answers

3
Elango On

try this is

    //after scanning 
    String data = "ABCD https://www.google.com fgh";
    String[] urls = data.split("\\s+");

    for (String url : urls) {
      if (url.startsWith("http://") || url.startsWith("https://")) {
                System.out.println(url);
                //it will print "https://www.google.com";
            }
        }