即使通过将EncodeHintType.MARGIN 设置为0,将二维码“点”矩阵转换为像素数据的算法也可以生成较小的边距(该算法强制每个点的像素数恒定,因此边距像素大小为像素大小除以二维码点大小的整数除法的余数。
但是您可以完全绕过这种“点到像素”的生成:您可以通过调用公共com.google.zxing.qrcode.encoder.Encoder 类直接计算二维码点阵,并自己生成像素图像。代码如下:
// Step 1 - generate the QRCode dot array
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(1);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
QRCode qrCode = Encoder.encode(what, ErrorCorrectionLevel.L, hints);
// Step 2 - create a BufferedImage out of this array
int width = qrCode.getMatrix().getWidth();
int height = qrCode.getMatrix().getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] rgbArray = new int[width * height];
int i = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
rgbArray[i] = qrCode.getMatrix().get(x, y) > 0 ? 0xFFFFFF : 0x000000;
i++;
} }
image.setRGB(0, 0, width, height, rgbArray, 0, width);
BufferedImage 到 PNG 数据的转换留给读者作为练习。您还可以通过设置每个点的固定像素数来缩放图像。
这种方式通常更优化,生成的图像尺寸尽可能小。如果您依赖客户端来缩放图像(无模糊),则每个点不需要超过 1 个像素。