Zxing 生成二维码和条形码去掉白边

本文介绍如何修改Zxing源码以去除生成的二维码和条形码周围的白边。通过分析QRCodeWriter和Code128Writer的encode方法,调整sideMargin和leftPadding等参数,实现了去除白边的效果。同时,文章探讨了保留一定白边的合理性,并分享了关于成语故事的人生感悟。
摘要由CSDN通过智能技术生成

源码下载:

https://github.com/AndroidZmm123/ZxingApplication

需求:根据输入内容,生成条形码或者二维码。

我们大多数会选择Zxing。因为jar包较小。且使用简单。根据内容生成二维码的工具类也是一搜一大堆。上面的源码里面也提供了一个。但是我们仔细看了下。会发现。不管生成的是条形码还是二维码都会有一部分的白边。如图:

我们可以看到周围有白边。那我们怎么去掉呢。

我们先把zxing的源码下载下来。然后看下这个白边是如果产生的。

首先是二维码的。

            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
                heightPix, hints);

这是根据我们输入的内容。产生一个矩阵。我们可以看到QRCodeWriter的encode()方法里面的最后两行:

   QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints);
        return renderResult(code, width, height, quietZone);

第一句是将我们输入的内容转换成code.不涉及宽高。

第二句是将code转换成矩阵。加入白边的代码就在这里面。

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 qrWidth = inputWidth;
        int qrHeight = inputHeight;

        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 100x1
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值