二维码又称二维条码,常见的二维码为QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型。
二维码其实就是一种编码技术,只是这种编码技术是用在图片上了,将给定的一些文字,数字转换为一张经过特定编码的图片,而解析二维码则相反,就是将一张经过编码的图片解析为数字或者文字。
使用Maven项目,依赖:
<!--https://mvnrepository.com/artifact/com.google.zxing/core-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<!--https://mvnrepository.com/artifact/com.google.zxing/javase-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
完整代码:
package com.miraclegenesis.api.controller.coupon;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.miraclegenesis.common.service.cooperation.CouponCodeCooperationService;
import org.junit.Test;
import com.google.zxing.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* 二維碼生成工具
*/
public class QRCodeController {
@Resource
private CouponCodeCooperationService cooperationService;
@Test
public void generateQRCode() throws WriterException, IOException {
//生成一个二维码
//定义一个json格式的字符串,试用fastJson
//1.创建一个JsonObject对象
// JSONObject jsonObject = new JSONObject();
//2.给JsonObject对象中存放数据
// jsonObject.put("baidu","www.baidu.com");
//3.json对象转换为json格式的字符串
// String content = jsonObject.toString();
String content = "http://ip:port/#/XXX?code=123456";
System.out.println(content);
//二维码的宽高
int width = 300;
int height = 300;
//创建map集合
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//创建一个矩阵对象
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
//生成的路径
String filePath = "D:\\qrcode";
String fileName = "123456.jpg";
//创建一个路径对象
Path path = FileSystems.getDefault().getPath(filePath, fileName);
//将矩阵对象生成一个图片
MatrixToImageWriter.writeToPath(bitMatrix, "jpg", path);
System.out.println("成功生成二维码图片");
}
}