欢迎大家去我的博客逛逛
前言
这里讲解一下条形码与二维码的基础知识与应用.
目录:
概念
条形码(barcode)
- 以一组宽度不同的黑条和空白,安照一定编码规则,用来表示一组信息的图形标识.
- 标识一串数字或字母.
- 一般容量小于30个数字或字母
二维码(QRcode)
- 又叫二维条形码.
- 用特定的几何图形按照一定规律在平面上分布的黑白相间的图形.
- 能够存储数字,字母,汉字,图片等.
- 字符集128个字符
- 可存储<几十kb
- 抗损坏
实践
常用类包
名称 | 特点 |
---|---|
Zxing(Google) | 支持1D,2D的barcode |
Barcode4J | 纯java生成,只负责生成,不负责解析 |
Zxing
Maven依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
条形码
/**
* generateCode 根据code生成相应的一维码
* @param file 一维码目标文件
* @param code 一维码内容
* @param width 图片宽度
* @param height 图片高度
*/
public static void generateCode(File file, String code, int width, int height) {
//定义位图矩阵BitMatrix
BitMatrix matrix = null;
try {
// 使用code_128格式进行编码生成100*25的条形码
MultiFormatWriter writer = new MultiFormatWriter();
matrix = writer.encode(code,BarcodeFormat.CODE_128, width, height, null);
//matrix = writer.encode(code,BarcodeFormat.EAN_13, width, height, null);
} catch (WriterException e) {
e.printStackTrace();
}
//将位图矩阵BitMatrix保存为图片
try (FileOutputStream outStream = new FileOutputStream(file)) {
ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png",
outStream);
outStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* readCode 读取一张一维码图片
* @param file 一维码图片名字
*/
public static void readCode(File file){
try {
BufferedImage image = ImageIO.read(file);
if (image == null) {
return;
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
Result result = new MultiFormatReader().decode(bitmap, hints);
System.out.println("条形码内容: "+result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
二维码
/*
* 定义二维码的宽高
*/
private static int WIDTH = 300;
private static int HEIGHT = 300;
private static String FORMAT = "png";//二维码格式
//生成二维码
public static void generateQRCode(File file, String content) {
//定义二维码参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置容错等级
hints.put(EncodeHintType.MARGIN, 2);//设置边距默认是5
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
Path path = file.toPath();
MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);//写到指定路径下
} catch (Exception e) {
e.printStackTrace();
}
}
//读取二维码
public static void readQrCode(File file) {
MultiFormatReader reader = new MultiFormatReader();
try {
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");//设置编码
Result result = reader.decode(binaryBitmap, hints);
System.out.println("解析结果:" + result.toString());
System.out.println("二维码格式:" + result.getBarcodeFormat());
System.out.println("二维码文本内容:" + result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
Barcode4J
Maven依赖
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-api</artifactId>
<version>4.3.1</version>
</dependency>
条形码
public static void generateFile(String msg, String path) {
File file = new File(path);
try {
Code39Bean bean = new Code39Bean();
//EAN13Bean bean = new EAN13Bean();
// dpi精度
final int dpi = 150;
// module宽度
//bean.setModuleWidth(0.2);
final double width = UnitConv.in2mm(2.0f / dpi);
bean.setWideFactor(3);
bean.setModuleWidth(width);
bean.doQuietZone(false);
String format = "image/png";
// 输出到流
BitmapCanvasProvider canvas = new BitmapCanvasProvider(new FileOutputStream(file), format, dpi,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
// 生成条形码
bean.generateBarcode(canvas, msg);
// 结束绘制
canvas.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
二维码
public static void main(String[] args) throws Exception {
BarcodeUtil util = BarcodeUtil.getInstance();
BarcodeGenerator gen = util.createBarcodeGenerator(buildCfg("datamatrix"));
OutputStream fout = new FileOutputStream("2dcode.png");
int resolution = 300;
BitmapCanvasProvider canvas = new BitmapCanvasProvider(fout, "image/png", resolution,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
gen.generateBarcode(canvas, "be the coder");
canvas.finish();
}
private static Configuration buildCfg(String type) {
DefaultConfiguration cfg = new DefaultConfiguration("barcode");
// Bar code type
DefaultConfiguration child = new DefaultConfiguration(type);
cfg.addChild(child);
// Human readable text position
DefaultConfiguration attr = new DefaultConfiguration("human-readable");
// DefaultConfiguration subAttr = new DefaultConfiguration("placement");
// subAttr.setValue("bottom");
// attr.addChild(subAttr);
// child.addChild(attr);
// datamatrix code has no human-readable part
// see http://barcode4j.sourceforge.net/2.1/symbol-datamatrix.html
attr = new DefaultConfiguration("height");
attr.setValue(50);
child.addChild(attr);
attr = new DefaultConfiguration("module-width");
attr.setValue("0.6");
child.addChild(attr);
return cfg;
}
总结
- 注意条形码种类
- 高并发时,注意生成速度
- api较多,需要多查询,练习