QRCode 方式
添加依赖:
<dependency> <groupId>org</groupId> <artifactId>QRCode</artifactId> <version>3.0</version></dependency>
代码:
Qrcode x = new Qrcode()x.setQrcodeErrorCorrect('M')//纠错等级x.setQrcodeEncodeMode('B')//N 代表数据 A 代表a-A B 代表其他字符x.setQrcodeVersion(7)//版本 String qrData = "https://www.baidu.com/" int width = 67 + 12 * (7 - 1)int height = 67 + 12 * (7 - 1)int pixoff = 2//偏移量 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 = qrData.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 * 3 + pixoff, i * 3 + pixoff, 3, 3) } } }} gs.dispose()bufferedImage.flush() try { ImageIO.write(bufferedImage, "png", new File("F:/qrcode.png"))} catch (IOException e) { e.printStackTrace()} ///////以上步骤已经生成了二维码,以下步骤为将二维码文件读取并转换为base64位字节流的过程//// byte[] data = null// 读取图片字节数组try { InputStream in = new FileInputStream("F:/qrcode.png") data = new byte[in.available()] in.read(data) in.close()} catch (IOException e) { e.printStackTrace()}// 对字节数组Base64编码BASE64Encoder encoder = new BASE64Encoder()return encoder.encode(data)// 返回Base64编码过的字节数组字符串
在上一步过程中,二维码源文件生成于 F:/qrcode.png 目录下。
为了方便微服务使用,我将源文件转换成base64字节流
在HTML文件中,将返回的字节流添加到<img>标签中即可,示例如下:
<img src="data:image/pngbase64,iVBORw0KGgoAAAANSUhEUgAAAIsAAACLCAIAAAD……QAAAAASUVO RK5CYII="/>
其中:“iVBORw0KGgoAAAANSUhEUgAAAIsAAACLCAIAAAD……QAAAAASUVO RK5CYII=”即为以上服务中返回的base64字节流
zxing方法
zxing是谷歌提供的一个生成而二维码的库,这里使用maven,所以先添加要使用的jar包的坐标。
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.2.1</version></dependency><dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.0.0</version></dependency>
生成二维码的基本代码还是比较简单的。// 定义要生成二维码的基本参数int width = 300int height = 300String type = "png"String content = "www.baidu.com"// 定义二维码的配置,使用HashMapHashMap hints = new HashMap()// 字符集,内容使用的编码hints.put(EncodeHintType.CHARACTER_SET, "UTF-8")// 容错等级,H、L、M、Qhints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M)// 边距,二维码距离边的空白宽度hints.put(EncodeHintType.MARGIN, 2)try { // 生成二维码对象,传入参数:内容、码的类型、宽高、配置 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints) // 定义一个路径对象 Path file = new File("D:/learn/code.png").toPath() // 生成二维码,传入二维码对象、生成图片的格式、生成的路径 MatrixToImageWriter.writeToPath(bitMatrix, type, file)} catch (WriterException e) { e.printStackTrace()} catch (IOException e) { e.printStackTrace()}
注意一点,因为上面的内容我们设置的是。扫码结果是这个字符串文本。如果想要扫码之后直接跳转到该链接,需要在网址前面加上协议。
既然有生成的方法,就有对应的解析二维码的方法。解析二维码就有些繁琐了。
try { // 声明一个解析二维码的对象 MultiFormatReader formatReader = new MultiFormatReader() // 生成一个文件对象,传入刚才生成二维码的路径 File file = new File("D:/learn/code.png") // 把文件对象转成一个图片对象 BufferedImage image = ImageIO.read(file) // 最后需要的是一个binaryBitmap对象。 BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image))) // 配置,解析时传入 HashMap hints = new HashMap() hints.put(EncodeHintType.CHARACTER_SET, "utf-8") // 解析得到一个Result对象,该对象包含二维码的信息 Result result = formatReader.decode(binaryBitmap, hints) // 分别输出二维码类型和内容的方法 System.out.println(result.getBarcodeFormat()) System.out.println(result.getText())} catch (IOException e) { e.printStackTrace()} catch (NotFoundException e) { e.printStackTrace()}