Java生成二维码、条形码
依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>
</dependency>
工具类
package com.nsk666.barcode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Hashtable;
/**
* 生成条形码,二维码工具类
*/
public class BarCodeUtil {
// 其他调用方法
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); //0xFF000000 黑色 0xFFFFFFFF 白色
}
}
return image;
}
/**
* 生成条形码
*
* @param msg 条形码内容,只能是数字形式
* @return 返回BufferedImage
*/
public static BufferedImage generalBarCode(String msg, int width, int height) {
Hashtable<EncodeHintType,String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
Code128Writer writer = new Code128Writer();
// 编码内容, 编码类型, 宽度, 高度, 设置参数
BitMatrix bitMatrix = writer.encode(msg, BarcodeFormat.CODE_128, width, height, hints);
BufferedImage image = toBufferedImage(bitMatrix);
return insertWords(image, msg);
} catch (Exception e) {
if (e instanceof IllegalArgumentException){
}
}
return null;
}
/**
* 二维码生成器
*
* @param text 二维码内容
*/
public static BufferedImage generalQRCode(String text, int width) {
Hashtable<EncodeHintType,String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, width, hints);
// 去除白边
return deleteWhite(bitMatrix);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//去白边的话,调用这个方法
private static BufferedImage deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1])) {
resMatrix.set(i, j);
}
}
}
return toBufferedImage(resMatrix);
}
/**
* 条形码下面加上文字
*
* @param image 条形码图片
* @param words 文字
* @return 返回BufferedImage
* @author fxbin
*/
public static BufferedImage insertWords(BufferedImage image, String words) {
if (words != null && !words.isEmpty()) {
int addHeight =20;
BufferedImage outImage = new BufferedImage(image.getWidth(),image.getHeight()+addHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = outImage.createGraphics();
// 抗锯齿
setGraphics2D(g2d);
// 设置白色
setColorWhite(g2d);
// 画条形码到新的面板
g2d.drawImage(image, 0,0, image.getWidth(), image.getHeight(), null);
// 画文字到新的面板
Color color = new Color(0, 0, 0);
g2d.setColor(color);
// 字体、字型、字号
g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
//文字长度
int strWidth = g2d.getFontMetrics().stringWidth(words);
//总长度减去文字长度的一半 (居中显示)
int wordStartX = ( image.getWidth() - strWidth) / 2;
//height + (outImage.getHeight() - height) / 2 + 12
int wordStartY = image.getHeight() +addHeight;
// 画文字
g2d.drawString(words, wordStartX, wordStartY);
g2d.dispose();
outImage.flush();
return outImage;
}
return null;
}
/**
* 设置 Graphics2D 属性 (抗锯齿)
*
* @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setGraphics2D(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(s);
}
/**
* 设置背景为白色
*
* @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setColorWhite(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
//填充整个屏幕
g2d.fillRect(0, 0, 600, 600);
//设置笔刷
g2d.setColor(Color.BLACK);
}
}
测试类
package com.nsk666.barcode;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* @author niushuaikui
* @description TODO
* @date 2024/1/22
*/
public class BarCodeTest {
public static void main(String[] args) throws IOException {
BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D mainPic = image.createGraphics();
String code = String.valueOf(System.currentTimeMillis());
System.out.println(code);
// 生成条形码
BufferedImage bimg = BarCodeUtil.generalQRCode(code,50);
if (bimg != null) {
mainPic.drawImage(bimg, 0, 0, 50, 50, null);
}
ImageIO.write(image,"png",new java.io.File("D:\\test\\qrcode.png"));
// 生成条形码
BufferedImage qrimg = BarCodeUtil.generalBarCode(code,150,50);
if (qrimg != null) {
mainPic.drawImage(qrimg, 0, 100, 200, 100, null);
}
ImageIO.write(image,"png",new java.io.File("D:\\test\\barcode.png"));
mainPic.dispose();
}
}
效果