java zxing条形码去掉两边空白,密度调整,固定条形码宽度

项目背景:由于条形码code不固定,生成的条形码密度,宽度不一致,有些条码密度太紧凑,导致扫码,扫不出来。

解决方法:重写zxing源码方法,看源码可以找到leftPadding决定了边距。

/**
   * @return a byte array of horizontal pixels (0 = white, 1 = black)
   */
  private static BitMatrix renderResult(boolean[] code, int width, int height, int sidesMargin) {
    int inputWidth = code.length;
    // Add quiet zone on both sides.
    int fullWidth = inputWidth + sidesMargin;
    int outputWidth = Math.max(width, fullWidth);
    int outputHeight = Math.max(1, height);

    int multiple = outputWidth / fullWidth;
    int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;

    BitMatrix output = new BitMatrix(outputWidth, outputHeight);
    for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
      if (code[inputX]) {
        output.setRegion(outputX, 0, multiple, outputHeight);
      }
    }
    return output;
  }

 这里只改了Code 128,

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wby
 * @date 2020/11/2
 */
public class CodeBar128Util implements Writer {

    private static String format = "png";//生成条形码图片类型

    public static void main(String[] args) throws Exception {
        getCodeBar("AMB02-0001-OCKSDJ-02", 335, 40);
    }

    /**
     * 生成条码方法
     *
     * @param content
     * @param width
     * @param height
     * @return
     * @throws Exception
     */
    public static void getCodeBar(String content, int width, int height) throws Exception {
        HashMap<EncodeHintType, Comparable> hints = new HashMap<EncodeHintType, Comparable>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 3);

        BitMatrix encode = new CodeBar128Util().encode(content, BarcodeFormat.CODE_128, width, height, hints);
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(encode);
        ImageIO.write(bufferedImage, "bmp", new FileOutputStream(new File("d://testBarcode_1.bmp")));
    }

    public static byte[] getCodeBar(String content) {
        HashMap<EncodeHintType, Comparable> hints = new HashMap<EncodeHintType, Comparable>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 3);

        ByteArrayOutputStream ot = new ByteArrayOutputStream();
        try {
            //设置宽高比例,自己调,这里主要是固定了宽度,高度不一致
            int width = new Code128Writer().encode(content).length;
            int height = width / 2;
            BitMatrix bm = new CodeBar128Util().encode(content, BarcodeFormat.CODE_128, width, height, hints);
            MatrixToImageWriter.writeToStream(bm, format, ot);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ot.toByteArray();
    }

    @Override
    public final BitMatrix encode(String contents, BarcodeFormat format, int width, int height)
            throws WriterException {
        return encode(contents, format, width, height, null);
    }

    /**
     * Encode the contents following specified format.
     * {@code width} and {@code height} are required size. This method may return bigger size
     * {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
     * {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
     * or {@code height}, {@code IllegalArgumentException} is thrown.
     */
    @Override
    public BitMatrix encode(String contents,
                            BarcodeFormat format,
                            int width,
                            int height,
                            Map<EncodeHintType, ?> hints) throws WriterException {
        if (contents.isEmpty()) {
            throw new IllegalArgumentException("Found empty contents");
        }

        if (width < 0 || height < 0) {
            throw new IllegalArgumentException("Negative size is not allowed. Input: "
                    + width + 'x' + height);
        }

        int sidesMargin = 2;
        if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) {
            sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
        }

        boolean[] code = new Code128Writer().encode(contents);
        return renderResult(code, width, height, sidesMargin);
    }

    /**
     * @return a byte array of horizontal pixels (0 = white, 1 = black)
     */
    private static BitMatrix renderResult(boolean[] code, int width, int height, int sidesMargin) {
        int inputWidth = code.length;
        int fullWidth = inputWidth;

        int outputWidth;
        if (width % inputWidth == 0) {
            outputWidth = width;
        }
        outputWidth = width > inputWidth ? width / inputWidth * inputWidth : (width / inputWidth + 1) * inputWidth;
        int outputHeight = Math.max(1, height);

        int multiple = outputWidth / fullWidth;
        int leftPadding = sidesMargin;

        BitMatrix output = new BitMatrix(outputWidth + 2 * sidesMargin, outputHeight);
        for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
            if (code[inputX]) {
                output.setRegion(outputX, 0, multiple, outputHeight);
            }
        }
        return output;
    }
}

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值