Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 364740a9 authored by Sadrul Chowdhury's avatar Sadrul Chowdhury
Browse files

[qr] Add a flag to generate inverted QR code.

Add a flag to the API to generate an inverted QR code. This is useful
when generating a QR code for a dark-mode UI, for example.

Bug: 270429486
Change-Id: I837c3f6d009568e8d501a5d8d1b54664233d64ee
parent cf2879cf
Loading
Loading
Loading
Loading
+16 −1
Original line number Diff line number Diff line
@@ -40,6 +40,19 @@ public final class QrCodeGenerator {
     */
    public static Bitmap encodeQrCode(String contents, int size)
            throws WriterException, IllegalArgumentException {
        return encodeQrCode(contents, size, /*invert=*/false);
    }

    /**
     * Generates a barcode image with {@code contents}.
     *
     * @param contents The contents to encode in the barcode
     * @param size     The preferred image size in pixels
     * @param invert   Whether to invert the black/white pixels (e.g. for dark mode)
     * @return Barcode bitmap
     */
    public static Bitmap encodeQrCode(String contents, int size, boolean invert)
            throws WriterException, IllegalArgumentException {
        final Map<EncodeHintType, Object> hints = new HashMap<>();
        if (!isIso88591(contents)) {
            hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
@@ -48,9 +61,11 @@ public final class QrCodeGenerator {
        final BitMatrix qrBits = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,
                size, size, hints);
        final Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
        int setColor = invert ? Color.WHITE : Color.BLACK;
        int unsetColor = invert ? Color.BLACK : Color.WHITE;
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                bitmap.setPixel(x, y, qrBits.get(x, y) ? Color.BLACK : Color.WHITE);
                bitmap.setPixel(x, y, qrBits.get(x, y) ? setColor : unsetColor);
            }
        }
        return bitmap;