Home > Enterprise >  Why do we use Hashtable when QR Code generation?
Why do we use Hashtable when QR Code generation?

Time:12-15

I have seen several examples for QR Code Generator in Java and most of them contains a parameter called hintMap. Here is one of the example:

public static BufferedImage getQRCode(String targetUrl, int width, 
    int height) {
    try {
        Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();

        hintMap.put(EncodeHintType.ERROR_CORRECTION, 
            ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(targetUrl, 
            BarcodeFormat.QR_CODE, width, height, hintMap);
        int CrunchifyWidth = byteMatrix.getWidth();

        BufferedImage image = new BufferedImage(CrunchifyWidth, 
            CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < CrunchifyWidth; i  ) {
            for (int j = 0; j < CrunchifyWidth; j  ) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }
        return image;
    } catch (WriterException e) {
        e.printStackTrace();
        throw new RuntimeException("Error getting QR Code");
    }

}

So, what is the usage of hintMap and why do we use it?

CodePudding user response:

The JavaDoc for QRCodeWriter#encode() says

hints - Additional parameters to supply to the encoder

The hints parameter is declared as Map<EncodeHintType,?> hints, so you can additionally look at the EncodeHintType JavaDoc for the different hints that you can pass into the method.

Some of the parameters are

  • CHARACTER_SET: Specifies what character encoding to use where applicable (type String)
  • ERROR_CORRECTION: Specifies what degree of error correction to use, for example in QR Codes.

So basically this hints parameter allows you to specify how the QR code should be generated without the need to create dozens of different encode() methods.


Why do we use it? When we want to specify special parameters for the QRCodeWriter#encode() method. If we don't need to specify these parameters we don't need it and don't use it.

  • Related