首先使用java语言制作二维码大概有两种方式
第一种就是利用google的zxing工具类
首先引入zxing的jar包
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
接下来创建生成方法
/**
*
* @param text 二维码内容
* @param width 二维码宽
* @param height 二维码高
* @param outPutPath 二维码生成保存路径
* @param imageType 二维码生成格式
*/
public void zxingCodeCreate(String text, int width, int height, String outPutPath, String imageType) {
Map<EncodeHintType, Object> his = new HashMap<EncodeHintType, Object>();
//设置编码字符集
his.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 指定纠错等级
his.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//设置二维码版本
his.put(EncodeHintType.QR_VERSION, 4);
//设置二维码边的空度,非负数
his.put(EncodeHintType.MARGIN, 0);
try {
//1、生成二维码
BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);
//2、获取二维码宽高
int codeWidth = encode.getWidth();
int codeHeight = encode.getHeight();
//3、将二维码放入缓冲流
BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < codeWidth; i++) {
for (int j = 0; j < codeHeight; j++) {
//4、循环将二维码内容定入图片
image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
}
}
File outPutImage = new File(outPutPath);
//如果图片不存在创建图片
if (!outPutImage.exists())
outPutImage.createNewFile();
//5、将二维码写入图片
ImageIO.write(image, imageType, outPutImage);
} catch (WriterException e) {
e.printStackTrace();
System.out.println("二维码生成失败");
} catch (IOException e) {
e.printStackTrace();
System.out.println("生成二维码图片失败");
}
}
@Test
public void testImgMin() {
// QRcode 二维码生成测试
//zxingCodeCreate("祝小仙女节日快乐",300, 300, "E:/borths.jpg", "jpg");
zxingCodeCreate("http://www.baidu.com", 33, 33, "D:/333233.jpg", "jpg");
}
执行testImgMin测试方法 就会再路径D:/333233.jpg生成二维码图片
第二种方式 利用Qrcode生成
首先下载Qrcode jar包下载地址
public void tesclearRecttImgQr() throws IOException {
Qrcode x = new Qrcode();
//N代表数字,A代表a-z,B代表其他字符
x.setQrcodeEncodeMode('B');
//设置纠错等级
x.setQrcodeErrorCorrect('L');
//设置版本号(1-40)
x.setQrcodeVersion(3);
String qrDate = "http://www.baidu.com";//
int width = 29;//二维码生成宽度
int height = 29;//二维码生成宽度
int pixoff = 0;//偏移量
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufferedImage.createGraphics();
gs.setBackground(Color.WHITE);
gs.setColor(Color.BLACK);
gs.clearRect(0, 0, width, height);
byte[] d = qrDate.getBytes("UTF-8");
if (d.length > 0 && d.length < 120) {
boolean[][] s = x.calQrcode(d);
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s.length; j++) {
if (s[j][i]) {
gs.fillRect(j, i, 1, 1);
}
}
}
}
gs.dispose();
bufferedImage.flush();
//二维码生成类型 及路径
ImageIO.write(bufferedImage, "png", new File("D:/2222222.png"));
}
执行这个测试方法即可生成二维码