package com.hdl.sdk.sourceos.qrcode;
|
|
import android.graphics.Bitmap;
|
import android.text.TextUtils;
|
|
import com.google.zxing.BarcodeFormat;
|
import com.google.zxing.EncodeHintType;
|
import com.google.zxing.MultiFormatWriter;
|
import com.google.zxing.WriterException;
|
import com.google.zxing.common.BitMatrix;
|
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
|
import java.util.HashMap;
|
import java.util.Map;
|
|
/**
|
* Created by Tong on 2021/11/8.
|
* 二维码
|
*/
|
public class QRCodeUtils {
|
|
|
/**
|
* 生成二维码
|
*/
|
public static Bitmap createQRCode(String txt, int width, int height, int margin) throws WriterException {
|
Bitmap bitmap = Bitmap.createBitmap(width, height,
|
Bitmap.Config.ARGB_8888);
|
createQRCode(bitmap, txt, width, height, margin);
|
return bitmap;
|
}
|
|
|
/**
|
* 生成二维码
|
*/
|
public static void createQRCode(Bitmap bitmap, String txt, int width, int height, int margin) throws WriterException {
|
|
if (TextUtils.isEmpty(txt)) {
|
return;
|
}
|
|
Map<EncodeHintType, Object> hints = new HashMap<>();
|
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
|
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
|
if (margin >= 0) {
|
hints.put(EncodeHintType.MARGIN, margin);
|
}
|
|
|
// 生成二维矩阵
|
BitMatrix matrix = new MultiFormatWriter().encode(txt,
|
BarcodeFormat.QR_CODE, width, height, hints);
|
|
// 二维矩阵转为一维像素数组,也就是一直横着排了
|
int[] pixels = new int[width * height];
|
for (int y = 0; y < height; y++) {
|
for (int x = 0; x < width; x++) {
|
if (matrix.get(x, y)) {
|
pixels[y * width + x] = 0xff000000;
|
} else {
|
pixels[y * width + x] = 0xffffffff;
|
}
|
}
|
}
|
|
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
|
}
|
|
|
}
|