如何用java生成二维码?
QRCode 方式
添加依赖:
代码:
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文件中,将返回的字节流添加到标签中即可,示例如下:
其中:“iVBORw0KGgoAAAANSUhEUgAAAIsAAACLCAIAAAD……QAAAAASUVO RK5CYII=”即为以上服务中返回的base64字节流
zxing方法zxing是谷歌提供的一个生成而二维码的库,这里使用maven,所以先添加要使用的jar包的坐标。
注意一点,因为上面的内容我们设置的是。扫码结果是这个字符串文本。如果想要扫码之后直接跳转到该链接,需要在网址前面加上协议。
既然有生成的方法,就有对应的解析二维码的方法。解析二维码就有些繁琐了。
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();}