Search code examples
javacolorszxingrgba

How to write qrcodes with zxing using HTML colors


I'm trying to write a colored qrcode using Google's zxing library in Java. It works fine with this example, which seems to use ARGB colors.

Unfortunately I have to use HTML/Hex values for colors in my application, so I tried to figure out how I can build or convert it.

I've alreday build an RGB color and used the alpha value as its prefix. But while a RGB value could be up to 255 - 3 digits, the parameter in MatrixToImageWriter only seems to work with 8 digits. That means that there are only two digits per color.

What Kind of value ist this "MatrixToImageConfig(-10223615,-1)"? Can somebody please explain me those color values or give me an example how to calculate HTML to this?

Thank you!

QRCodeWriter qrCodeWriter = new QRCodeWriter();

BitMatrix bitMatrix = qrCodeWriter.encode(createQRCodeContent, BarcodeFormat.QR_CODE, createQRCodeSize, createQRCodeSize);

// Color
MatrixToImageConfig conf = new MatrixToImageConfig(-10223615,-1);

BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(bitMatrix, conf);

File qrfile = new File (targetPath);

ImageIO.write(qrcode, "png", qrfile);

Solution

  • Answer to my own question:

    String hex = "#ffffff00";
    
    //-16711681 in ARGB int, for example used in Google's zxing library for colored qrcodes
    System.out.println(toARGB(hex));
    
    public static int toARGB(String nm) {
    Long intval = Long.decode(nm);
    long i = intval.intValue();
    
    int a = (int) ((i >> 24) & 0xFF);
    int r = (int) ((i >> 16) & 0xFF);
    int g = (int) ((i >> 8) & 0xFF);
    int b = (int) (i & 0xFF);
    
    return ((a & 0xFF) << 24) |
            ((b & 0xFF) << 16) |
            ((g & 0xFF) << 8)  |
            ((r & 0xFF) << 0);
    }