zxing 二维码生成 点阵数 边距控制

2019-11-29  本文已影响0人  Trulon

在使用zxing生成二维码的过程中遇到二维码的边距,点阵数无法控制等问题,最后通过查看源码找到解决方案,做个记录。

生成二维码的关键要素:

关于二维码

二维码规范中定义了1-40种版本,不同的版本就是点阵数不同,点阵数也将决定最多能容纳的信息。

参考
https://www.qrcode.com/en/about/version.html

这里说的点阵数就是上面页面里的“Modules”

可以看到相同点阵数,容错级别越高,留给原始内容字符串的空间就少,
不同的原始内容字符串类型(纯数字,包括大写字母,其他二进制数据)占用的空间不同。

zxing的逻辑

zxing根据输入字符串类型,长度,容错级别,计算出信息数据,
选出一个能够容纳信息数据的最小版本来绘制原始二维码点阵。事实上选择更大点阵的版本也是可以的,只要能够容纳信息数据就可以。

然后根据设置的图像宽高和留白边距和生成一个画布,
将原始二维码点阵自适应整倍缩放居中填充到画布上。

自动选择最小点阵,导致所给字符串内容长度不同,出来的点阵数不同,观感不一致

整倍缩放导致实际留白可能比设置的要大

com.google.zxing.qrcode.QRCodeWriter 类生成二维码

  @Override
  public BitMatrix encode(String contents,
                          BarcodeFormat format,
                          int width,
                          int height,
                          Map<EncodeHintType,?> hints) throws WriterException {

    //一些校验逻辑省略...

    // 容错级别未传则默认L 边距未传则默认4像素
    ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
    int quietZone = QUIET_ZONE_SIZE;
    if (hints != null) {
      ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION);
      if (requestedECLevel != null) {
        errorCorrectionLevel = requestedECLevel;
      }
      Integer quietZoneInt = (Integer) hints.get(EncodeHintType.MARGIN);
      if (quietZoneInt != null) {
        quietZone = quietZoneInt;
      }
    }

    // 生成二维码原始点阵数据
    QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints);

    // 生成图片
    return renderResult(code, width, height, quietZone);
  }

Encoder.encode(contents, errorCorrectionLevel, hints);

这个方法生成原始点阵数据,内部有一个chooseVersion方法,选择最小点阵版本的逻辑

  // zxing原码,选择最小点阵版本
 private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException {
    // In the following comments, we use numbers of Version 7-H.
    for (int versionNum = 1; versionNum <= 40; versionNum++) {
      Version version = Version.getVersionForNumber(versionNum);
      // numBytes = 196
      int numBytes = version.getTotalCodewords();
      // getNumECBytes = 130
      Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
      int numEcBytes = ecBlocks.getTotalECCodewords();
      // getNumDataBytes = 196 - 130 = 66
      int numDataBytes = numBytes - numEcBytes;
      int totalInputBytes = (numInputBits + 7) / 8;
      if (numDataBytes >= totalInputBytes) {
        return version;
      }
    }
    throw new WriterException("Data too big");
  }

renderResult(code, width, height, quietZone)

这个方法则是根据目标宽高绘制二维码结果图片,内部可以看到留白控制和缩放填充逻辑

  // zxing原码,根据点阵数据缩放,目标图片宽高,留白设置 缩放居中渲染结果图片
private static BitMatrix renderResult(QRCode code, int width, int height, int quietZone) {
    ByteMatrix input = code.getMatrix();
    if (input == null) {
      throw new IllegalStateException();
    }
    int inputWidth = input.getWidth();
    int inputHeight = input.getHeight();
    int qrWidth = inputWidth + (quietZone * 2);
    int qrHeight = inputHeight + (quietZone * 2);
    int outputWidth = Math.max(width, qrWidth);
    int outputHeight = Math.max(height, qrHeight);

    int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight);
    // Padding includes both the quiet zone and the extra white pixels to accommodate the requested
    // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
    // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
    // handle all the padding from 100x100 (the actual QR) up to 200x160.
    int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
    int topPadding = (outputHeight - (inputHeight * multiple)) / 2;

    BitMatrix output = new BitMatrix(outputWidth, outputHeight);

    for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
      // Write the contents of this row of the barcode
      for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
        if (input.get(inputX, inputY) == 1) {
          output.setRegion(outputX, outputY, multiple, multiple);
        }
      }
    }

    return output;
  }

精准控制点阵数与留白实现

看完面zxing的源码可以知道,若用zxing直接提供的可以控制的参数,除了自己掐准内容长度外,是不能确定他会选择那个点阵版本的。想到一个简单修改zxing源码的办法,借助javassist,运行时修改zxing的类定义,替换chooseVersion方法。加入一段逻辑,如果zxing选择的点阵版本太小,则getVersionForNumber(1-40)返回一个新的的目标点阵(参考二维码规范,找一个合适的点阵,当然还得比原来的大,不然信息保存不下)。然后设置目标宽高为点阵数的倍数,设置留白0,实现了点阵数,留白,宽高的精准控制。

全部代码实现:

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.decoder.Version;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

/**
 * 
 * 准确控制zxing生成二维码图片的点阵数,留白
 * 
 * @author churonglong 2019-11-29
 */
public class ZxingQRCodeGenerate {

    static final MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

    public static void main(String[] args) throws IOException {
        String qrCodeContent = "https://cn.bing.com";
        int qrCodeWidth = 74;

        BufferedImage bufferedImage = generateQRCode(qrCodeContent, qrCodeWidth);

        ImageIO.write(bufferedImage, "png", new File("/Users/churonglong/Trulon/toplog/qrcode.png"));
    }

    public static BufferedImage generateQRCode(String qrCodeContent, int qrCodeWidth) {

        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        try {
            qrcodeVersionChooseHack();
            BitMatrix matrix = multiFormatWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeWidth, hints);
            return MatrixToImageWriter.toBufferedImage(matrix);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    synchronized private static void qrcodeVersionChooseHack() throws Exception {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get("com.google.zxing.qrcode.encoder.Encoder");

        CtMethod cm = ctClass.getDeclaredMethod("chooseVersion");
        ctClass.removeMethod(cm);
        String method = "   private static com.google.zxing.qrcode.decoder.Version chooseVersion(int numInputBits, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ecLevel) throws com.google.zxing.WriterException {\n" +
                "       return ZxingQRCodeGenerate.chooseVersion(numInputBits,ecLevel);" +
                "   }";
        CtMethod make = CtMethod.make(method, ctClass);
        ctClass.addMethod(make);

        ctClass.toClass();
    }

    /**
     * @see com.google.zxing.qrcode.encoder.Encoder#chooseVersion(int, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel)
     */
    public static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException {
        // In the following comments, we use numbers of Version 7-H.
        for (int versionNum = 1; versionNum <= 40; versionNum++) {
            Version version = Version.getVersionForNumber(versionNum);
            // numBytes = 196
            int numBytes = version.getTotalCodewords();
            // getNumECBytes = 130
            Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
            int numEcBytes = ecBlocks.getTotalECCodewords();
            // getNumDataBytes = 196 - 130 = 66
            int numDataBytes = numBytes - numEcBytes;
            int totalInputBytes = (numInputBits + 7) / 8;
            if (numDataBytes >= totalInputBytes) {
                // hack 逻辑,优先选择 37*37 74*74 的版本
                if (versionNum <= 5) {
                    return Version.getVersionForNumber(5);
                }
                if (versionNum <= 14) {
                    return Version.getVersionForNumber(14);
                }
                return version;
            }
        }
        throw new WriterException("Data too big");
    }
}

原始问题:内容长度影响二维码点阵数,观感不一致

  1. 原本是37x37点数的二维码,在把原始内容长网址换成短链后,发现点阵数成了25*25,变粗了。


    长链37x37.png
短链25x25.png
  1. 先尝试在短链后面添加无意义的参数字符,形如https:aaa.com?x=xxxxxxxx,可以回到37*37。过程中发现内容重复,生成的二维码是有规律的,emmm~


    短链填充无意义参数.png

而且扫出来的地址带着无意义的参数,不那么严谨,放弃这个方案。

  1. 再尝试通过容错率控制点阵数,将复杂度由L 提高到 M,结果出来的码点阵数上去了,线细了,但是又带上了留白。


    提高容错率.png
  1. 由于二维码是用在小分辨率设备上,所占的物理像素固定是74*74,非常有限,如果二维码宽高点阵数不是他的整数倍可能存在失真的情况,
    25x25,37x37,74x74 这三种才是最优点阵数,因此需要找到一种可以生成指定点阵数,且控制不要留白二维码的办法。
最终.png
上一篇下一篇

猜你喜欢

热点阅读