/** * Author: 侯亚东 * Date: 2022-01-20 15:10 * Email: houyadong1@gome.com.cn * Des: 二维码生成工具类 */ public class ZxingUtils {
/** * 生成二维码Bitmap * * @param content 内容 * @param widthPix 图片宽度 * @param heightPix 图片高度 * @param isDeleteWhite 是否删除白色边框 * @return 生成的二维码Bitmap */ public static Bitmap createQRImage(String content, int widthPix, int heightPix, boolean isDeleteWhite) { try { Hashtable<EncodeHintType, Object> hints = new Hashtable<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.MARGIN, isDeleteWhite ? 1 : 0); BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints); if (isDeleteWhite) { //删除白边 matrix = deleteWhite(matrix); } widthPix = matrix.getWidth(); heightPix = matrix.getHeight(); int[] pixels = new int[widthPix * heightPix]; for (int y = 0; y < heightPix; y++) { for (int x = 0; x < widthPix; x++) { if (matrix.get(x, y)) { pixels[y * widthPix + x] = Color.BLACK; } else { pixels[y * widthPix + x] = Color.WHITE; } } } Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix); return bitmap; } catch (Exception e) { return null; } }
/** * 删除白色边框 * * @param matrix matrix * @return BitMatrix */ private static BitMatrix deleteWhite(BitMatrix matrix) { int[] rec = matrix.getEnclosingRectangle(); //这句是重点吧 int resWidth = rec[2] + 1; int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); resMatrix.clear(); for (int i = 0; i < resWidth; i++) { for (int j = 0; j < resHeight; j++) { if (matrix.get(i + rec[0], j + rec[1])) resMatrix.set(i, j); } } return resMatrix; } }
|