开发工具: IDEA
使用类库下载地址:https://mvnrepository.com/
下载文件:
https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1
https://mvnrepository.com/artifact/com.google.zxing/core/3.3.0
生成 二维码
public class TestOR_Code_Create {
public static void main(String[] args) throws WriterException, IOException {
//保存的位置
String path = "d:/info.png";
//生成的图片大小
int width = 400, height = 400;
//信息
String name = "哈罗沃德";
String company = "千锋教育";
String city = "重庆";
String job = "java 老司机";
StringBuilder info = new StringBuilder();
info.append(name);
info.append(company);
info.append(job);
info.append(city);
//解决乱码
byte[] bytes = info.toString().getBytes(Charset.defaultCharset());
String text = new String(bytes,Charset.forName("ISO-8859-1"));
generateQRCodeImage(text,width,height,path);
//提示,可不要
System.out.println("生成完毕...");
}
/**
* 封装一个 生成 二维码图片的工具方法
* @param text 生成的信息
* @param width 图片宽度
* @param height 图片高度
* @param filePath 生成后保存的位置
* @throws WriterException
* @throws IOException
*/
public static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException, IOException {
//创建一个图片生成器
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//创建一个BitMatrix 比特矩阵 对象 ,数据填充到矩阵上
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
//创建路径对象
Path path = FileSystems.getDefault().getPath(filePath);
//输出像素矩阵到图片
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
}
解析 二维码
public class TestOR_Code_Read {
public static void main(String[] args) throws Exception {
//指定二维码图片的位置
String filepath = "d:/info.png";
//调用封装好的解析方法
String s = parseORcode(filepath);
//展示解析结果
System.out.println(s);
}
/**
* 封装一个解析图片二维码的方法,用于提取二维码中的内容
* @param filepath 图片所在位置
* @return 提取的信息
* @throws Exception
*/
public static String parseORcode(String filepath) throws Exception{
//创建一个图片对象接收
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
//获得图片光线源
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
//获得图片二维源
Binarizer binarizer = new HybridBinarizer(source);
//获得位图
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
//创建图片配置信息map
HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
//设置编码信息
decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
//获得结果
Result result = new MultiFormatReader().decode(bitmap, decodeHints);
//返回结果
return result.getText();
}
}