1 /* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.tv.settings.connectivity.util; 18 19 import android.graphics.Bitmap; 20 import android.graphics.Color; 21 22 import com.google.zxing.BarcodeFormat; 23 import com.google.zxing.EncodeHintType; 24 import com.google.zxing.MultiFormatWriter; 25 import com.google.zxing.WriterException; 26 import com.google.zxing.common.BitMatrix; 27 28 import java.nio.charset.CharsetEncoder; 29 import java.nio.charset.StandardCharsets; 30 import java.util.HashMap; 31 import java.util.Map; 32 33 /** 34 * A class that generates a QR code image from a string. 35 * Borrowed from packages/apps/Settings/src/com/android/settings/wifi/qrcode/QrCodeGenerator.java 36 */ 37 public final class QrCodeGenerator { 38 /** 39 * Generates a QR code image with {@code contents}. 40 * 41 * @param contents The contents to encode in the barcode 42 * @param size The preferred image size in pixels 43 * @return Barcode bitmap 44 */ encodeQrCode(String contents, int size)45 public static Bitmap encodeQrCode(String contents, int size) 46 throws WriterException, IllegalArgumentException { 47 final Map<EncodeHintType, Object> hints = new HashMap<>(); 48 if (!isIso88591(contents)) { 49 hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name()); 50 } 51 52 final BitMatrix qrBits = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, 53 size, size, hints); 54 final Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565); 55 for (int x = 0; x < size; x++) { 56 for (int y = 0; y < size; y++) { 57 bitmap.setPixel(x, y, qrBits.get(x, y) ? Color.BLACK : Color.WHITE); 58 } 59 } 60 return bitmap; 61 } 62 isIso88591(String contents)63 private static boolean isIso88591(String contents) { 64 CharsetEncoder encoder = StandardCharsets.ISO_8859_1.newEncoder(); 65 return encoder.canEncode(contents); 66 } 67 } 68