条形码和二维码在生活中有广泛应用,在食品零售行业、图书馆等场景中条形码在商品信息中扮演了重要地位,二维码也在日常生活中的检票、验票、交友等各种场景中扮演着重要角色。下面介绍下如何手搓这两种码。

依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- 二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>

<!-- 条形码 -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>

<!-- SVG转换成PNG -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-transcoder</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-codec</artifactId>
<version>1.16</version>
</dependency>

条形码

输出png格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@SneakyThrows  
public static void generateAtCode128ToPNG(String msg, String filePath, Double fontSize) {
if (StrUtil.isBlank(msg)) {
log.error("生成条形码内容不能为空");
return;
}
Code128Bean code128Bean = new Code128Bean();
code128Bean.doQuietZone(true);
code128Bean.setBarHeight(HEIGHT);
code128Bean.setModuleWidth(UnitConv.in2mm(1.5f / DPI));
code128Bean.setFontSize(fontSize);
String format = "image/png";
ByteArrayOutputStream os = new ByteArrayOutputStream();
BitmapCanvasProvider canvasProvider = new BitmapCanvasProvider(os, format, DPI, BufferedImage.TYPE_BYTE_BINARY, false, 0);
code128Bean.generateBarcode(canvasProvider, msg);
canvasProvider.finish();
byte[] bytes = os.toByteArray();
FileUtil.writeBytes(bytes, new File(filePath));
}

输出svg格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static void generateAtCode128ToSVG(String msg, String filePath, Double fontSize) {  
if (StrUtil.isBlank(msg)) {
log.error("生成条形码内容不能为空");
return;
}
Code128Bean code128Bean = new Code128Bean();
// 条形码宽度
code128Bean.setModuleWidth(UnitConv.in2mm(1.5f / DPI));
// 条形码高度
code128Bean.setBarHeight(HEIGHT);
// 设置两侧留白
code128Bean.doQuietZone(true);
// 字体大小
code128Bean.setFontSize(fontSize);
// 输出到流,创建 SVGCanvasProvider 对象用来生成 SVG 格式条形码
SVGCanvasProvider canvas = new SVGCanvasProvider(false, 0);
// 生成条形码,将条形码绘制到 canvas 上
code128Bean.generateBarcode(canvas, msg);
// 获取生成的条形码 DOM 片段
DocumentFragment domFragment = canvas.getDOMFragment();
// 将 DOM 片段转换成 SVG TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(domFragment);
StreamResult result = new StreamResult(filePath);
// 将转换后的SVG输出到指定文件
transformer.transform(source, result);
}

解析条形码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@SneakyThrows  
public static String parseBarCode(String srcImagePath) {
BufferedImage bufferedImage;
if (srcImagePath.endsWith(".svg")) {
try (FileInputStream inputStream = new FileInputStream(new File(srcImagePath));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// 创建 SVG 转 PNG 转码输入
TranscoderInput input = new TranscoderInput(inputStream);
// PNG 转码器对象
PNGTranscoder transcoder = new PNGTranscoder();
transcoder.addTranscodingHint(PNGTranscoder.KEY_BACKGROUND_COLOR, Color.WHITE);
// 创建转码输出流
TranscoderOutput output = new TranscoderOutput(outputStream);
// 执行 SVG 转 PNG 转换
transcoder.transcode(input, output);
// 获取 PNG 字节数据
byte[] pngBytes = outputStream.toByteArray();

// 将字节数据转为 BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(pngBytes));
// 输出图片文件以便调试
//ImageIO.write(bufferedImage, "PNG", new File("output.png"));
} catch (Exception e) {
throw new IOException("Failed to convert SVG to PNG", e);
}
} else {
// 如果是普通的图像文件,直接读取
bufferedImage = ImageIO.read(new File(srcImagePath));
}
// 确保图像读取成功
if (bufferedImage == null) {
throw new IOException("Failed to read the image, possibly invalid format.");
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader formatReader = new MultiFormatReader();
Result result = formatReader.decode(bitmap);
return result.getText();
}

二维码

静态常量参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**  
* 二维码宽度
*/
private static final int CODE_WIDTH = 400;

/**
* 二维码高度
*/
private static final int CODE_HEIGHT = 400;

/**
* 二维码前景色(黑色)
*/private static final int FRONT_COLOR = 0x000000;

/**
* 图标宽度
*/
private static final int IMAGE_WIDTH = 100;

/**
* 图标高度
*/
private static final int IMAGE_HEIGHT = 100;

/**
* 图标一半宽度
*/
private static final int IMAGE_HALF_WIDTH = 50;

/**
* 是否补白
*/
private static final boolean HAS_FILLER = true;

/**
* 二维码背景色(白色)
*/private static final int BACKGROUND_COLOR = 0xFFFFFF;

/**
* 边框宽度
*/
private static final int FRAME_WIDTH = 2;

常规二维码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**  
* 生成二维码并保存图片
*/
@SneakyThrows
public static void createCodeToFile(String codeContent, File codeImageDir, String fileName) {
if (StrUtil.isBlank(codeContent)) {
log.info("二维码内容为空,进行操作失败");
return;
}
if (ObjectUtil.isNull(codeImageDir) || codeImageDir.isFile()) {
codeImageDir = FileSystemView.getFileSystemView().getHomeDirectory();
log.info("二维码存放目录为空,默认存放在桌面");
}
if (!codeImageDir.exists()) {
codeImageDir.mkdirs();
log.info("二维码存放目录不存在,开始创建");
}
if (StrUtil.isBlank(fileName)) {
fileName = System.currentTimeMillis() + ".png";
log.info("二维码图片文件名为空,随机生成png格式文件");
}
// 设置编码字符集、误差校正、二维码边距
HashMap<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 1);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
// BitMatrix:二维码矩阵对象,表示二维码的黑白点阵对象
BitMatrix bitMatrix = multiFormatWriter.encode(codeContent, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < CODE_WIDTH; x++) {
for (int y = 0; y < CODE_HEIGHT; y++) {
bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
}
}
// 保存二维码图片
File file = new File(codeImageDir, fileName);
ImageIO.write(bufferedImage, "png", file);
log.info("二维码图片生成成功:" + file.getPath());
}

内嵌图片二维码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**  
* 生成二维码嵌入图片
*/
@SneakyThrows
public static BufferedImage genBarCodeWithImg(String codeContent, String srcImagePath) {
// 读取源图像
BufferedImage scaleImage = scale(srcImagePath);
int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
for (int i = 0; i < scaleImage.getWidth(); i++) {
for (int j = 0; j < scaleImage.getHeight(); j++) {
srcPixels[i][j] = scaleImage.getRGB(i, j);
}
}
HashMap<EncodeHintType, Object> hint = new HashMap<>();
hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hint.put(EncodeHintType.MARGIN, 1);
// 生成二维码
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix matrix = multiFormatWriter.encode(codeContent, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hint);
int halfW = matrix.getWidth() / 2;
int halfH = matrix.getHeight() / 2;
int[] pixels = new int[CODE_HEIGHT * CODE_WIDTH];
// 二维矩阵转换为一维像素数组
for (int y = 0; y < matrix.getHeight(); y++) {
for (int x = 0; x < matrix.getWidth(); x++) {
// 读取图片
if (x > halfW - IMAGE_HALF_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH
&& y < halfH + IMAGE_HALF_WIDTH) {
pixels[y * CODE_WIDTH + x] = srcPixels[x - halfW + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
} else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& y < halfH - IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH
&& y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)){
// 在图片四周形成边框
pixels[y * CODE_WIDTH + x] = BACKGROUND_COLOR;
} else {
// 此处修改二维码的颜色
pixels[y * CODE_WIDTH + x] = matrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR;
}
}
}
BufferedImage image = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, CODE_WIDTH, CODE_HEIGHT, pixels);
return image;
}

/**
* 对传入的原始文件进行缩放以生成符合要求的图标
*/
@SneakyThrows
public static BufferedImage scale(String srcImageFile) {
// 缩放比例
double radio = 0.0;
File file = new File(srcImageFile);
BufferedImage srcImage = ImageIO.read(file);
Image destImage = srcImage.getScaledInstance(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.SCALE_SMOOTH);
// 计算比例
if ((srcImage.getHeight() > IMAGE_HEIGHT) || (srcImage.getWidth() > IMAGE_WIDTH)) {
if ((srcImage.getHeight() > srcImage.getWidth())) {
radio = (new Integer(IMAGE_HEIGHT)).doubleValue() / srcImage.getHeight();
} else {
radio = (new Integer(IMAGE_WIDTH)).doubleValue() / srcImage.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(radio, radio), null);
destImage = op.filter(srcImage, null);
}
// 补白
if (HAS_FILLER) {
BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.white);
graphics.fillRect(10, 10, IMAGE_WIDTH, IMAGE_HEIGHT);
graphics.drawRect(100, 360, IMAGE_WIDTH, IMAGE_HEIGHT);
if (IMAGE_WIDTH == destImage.getHeight(null)) {
graphics.drawImage(destImage, 0,
(IMAGE_HEIGHT - destImage.getHeight(null)) / 2,
destImage.getWidth(null), destImage.getHeight(null),
Color.white, null);
Shape shape = new RoundRectangle2D.Float(0, (IMAGE_HEIGHT - destImage.getHeight(null)) / 2, IMAGE_WIDTH, IMAGE_WIDTH, 20, 20);
graphics.setStroke(new BasicStroke(5f));
graphics.draw(shape);
} else {
graphics.drawImage(destImage,
(IMAGE_WIDTH - destImage.getWidth(null)) / 2, 0,
destImage.getWidth(null), destImage.getHeight(null),
Color.white, null);
Shape shape = new RoundRectangle2D.Float((IMAGE_WIDTH - destImage.getWidth(null)) / 2, 0, IMAGE_WIDTH, IMAGE_WIDTH, 20, 20);
graphics.setStroke(new BasicStroke(5f));
graphics.draw(shape);
}
graphics.dispose();
destImage = image;
}
return (BufferedImage) destImage;
}

解析二维码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static String parseQRCode(File file) {  
String resultStr = null;
if (file == null || file.isDirectory() || !file.exists()) {
return resultStr;
}
try {
// 读取网络图片为内存缓冲图像
BufferedImage bufferedImage = ImageIO.read(file);
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
// 读取二维码图像数据,转换成BinaryBitmap二进制位图对象
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);
resultStr = result.getText();
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
log.error("图片非二维码格式图片:" + file.getPath());
}
return resultStr;
}

使用验证

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) throws IOException {  
String msg = "挪车电话:15107079636";
createCodeToFile(msg, new File("Q:/myproject/my-practice/java-tool/src/main/resources"), "二维码.png");
File file = new File("Q:/myproject/my-practice/java-tool/src/main/resources/二维码.png");
String result = parseQRCode(file);
System.out.println(result);
BufferedImage bufferedImage = genBarCodeWithImg(msg, "Q:/myproject/my-practice/java-tool/src/main/resources/微信头像.jpg");
File file1 = new File("Q:/myproject/my-practice/java-tool/src/main/resources/二维码名片.png");
ImageIO.write(bufferedImage, "png", file1);
}