@Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints)throws WriterException {
Writer writer; switch (format) { case EAN_8: writer = new EAN8Writer(); break; case EAN_13: writer = new EAN13Writer(); break; case UPC_A: writer = new UPCAWriter(); break; case QR_CODE: writer = new QRCodeWriter(); break; case CODE_39: writer = new Code39Writer(); break; case CODE_128: writer = new Code128Writer(); break; case ITF: writer = new ITFWriter(); break; case PDF_417: writer = new PDF417Writer(); break; case CODABAR: writer = new CodaBarWriter(); break; case DATA_MATRIX: writer = new DataMatrixWriter(); break; case AZTEC: writer = new AztecWriter(); break; default: thrownew IllegalArgumentException("No encoder available for format " + format); } return writer.encode(contents, format, width, height, hints); }
@Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints)throws WriterException { if (format != BarcodeFormat.CODE_128) { thrownew IllegalArgumentException("Can only encode CODE_128, but got " + format); } returnsuper.encode(contents, format, width, height, hints); }
@Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints)throws WriterException { if (contents.isEmpty()) { thrownew IllegalArgumentException("Found empty contents"); }
if (width < 0 || height < 0) { thrownew IllegalArgumentException("Negative size is not allowed. Input: " + width + 'x' + height); }
int sidesMargin = getDefaultMargin(); if (hints != null) { Integer sidesMarginInt = (Integer) hints.get(EncodeHintType.MARGIN); if (sidesMarginInt != null) { sidesMargin = sidesMarginInt; } }
publicintgetDefaultMargin(){ // CodaBar spec requires a side margin to be more than ten times wider than narrow space. // This seems like a decent idea for a default for all formats. return10; }
privatestatic 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;
//配置条码参数 Map<EncodeHintType,Object> hints = new HashMap<>(); //设置条码两边空白边距为0,默认为10,如果宽度不是条码自动生成宽度的倍数则MARGIN无效 hints.put(EncodeHintType.MARGIN, 0);
//为了无边距,需设置宽度为条码自动生成规则的宽度 int width = new Code128Writer().encode(contents).length; //前端可控制高度,不影响识别 int height = 70; //条码放大倍数 int codeMultiples = 1; //获取条码内容的宽,不含两边距,当EncodeHintType.MARGIN为0时即为条码宽度 int codeWidth = width * codeMultiples;