一、介绍:生成二维码有很多种方法,比如微信公众号的生成二维码,但是这个二维码只能用微信扫描且会(可以带参数)自动跳转到微信的公众号页面,不支持跳转到其他网页。这里说的二维码是扫描(微信、QQ、浏览器等扫描)可以跳转到指定网址的二维码。二维码最早是由日本一家公司开发的,并且该二维码主要有两种方式:一种是QRCode 插件产生于日本 ;另一种是ZXing 插件由谷歌开发的。
二、ZXing插件开发:
1、引入依赖
<!-- 生成二维码,spring boot 的maven项目 导入响应jar包 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.1.0</version> </dependency>
|
2、生成的代码:
package com.demo.controller;
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix;
public class A {
private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF;
public static void main(String[] args) { try { boolean flag = generateCode("518"); if (flag) { System.out.println("成功生成二维码"); } } catch (WriterException | IOException e) { System.err.println("生成二维码失败"); e.printStackTrace(); } }
public static boolean generateCode(String productId) throws WriterException, IOException { String text = "https://www.baidu.com/?uudi=" + productId; String path = "E:/"; int width = 400; int height = 400; String format = "jpg"; Hashtable<EncodeHintType, Object> ht = new Hashtable<EncodeHintType, Object>(); ht.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, ht); File outputFile = new File(path); if (!outputFile.exists()) { outputFile.mkdir(); }
int b_width = bitMatrix.getWidth(); int b_height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(b_width, b_height, BufferedImage.TYPE_3BYTE_BGR); for (int x = 0; x < b_width; x++) { for (int y = 0; y < b_height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE); } } ImageIO.write(image, format, new File(path + "/code." + format));
return true; } }
|