1 /* 2 * Copyright (C) 2018 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.settings.wifi.qrcode; 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 public final class QrCodeGenerator { 34 /** 35 * Generates a barcode image with {@code contents}. 36 * 37 * @param contents The contents to encode in the barcode 38 * @param size The preferred image size in pixels 39 * @return Barcode bitmap 40 */ encodeQrCode(String contents, int size)41 public static Bitmap encodeQrCode(String contents, int size) 42 throws WriterException, IllegalArgumentException { 43 final Map<EncodeHintType, Object> hints = new HashMap<>(); 44 if (!isIso88591(contents)) { 45 hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name()); 46 } 47 48 final BitMatrix qrBits = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, 49 size, size, hints); 50 final Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565); 51 for (int x = 0; x < size; x++) { 52 for (int y = 0; y < size; y++) { 53 bitmap.setPixel(x, y, qrBits.get(x, y) ? Color.BLACK : Color.WHITE); 54 } 55 } 56 return bitmap; 57 } 58 isIso88591(String contents)59 private static boolean isIso88591(String contents) { 60 CharsetEncoder encoder = StandardCharsets.ISO_8859_1.newEncoder(); 61 return encoder.canEncode(contents); 62 } 63 } 64