一,zxing是什么?
1,zxing的用途
如果我們做二維碼的生成和掃描,通常會用到zxing這個庫,
ZXing是一個開源的,用Java實現的多種格式的1D/2D條碼圖像處理庫。
zxing還可以實現使用手機的內置的攝像頭完成條形碼的掃描及解碼
2,zxing官方項目地址:
https://github.com/zxing/zxing
說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,演示項目的相關信息
1,項目地址
https://github.com/liuhongdi/qrcode
2, 項目功能說明:
生成二維碼直接展示
生成二維碼保存成圖片
解析二維碼圖片中的文字信息
3,項目結構,如圖:
三,配置文件說明
1,pom.xml
<!--qrcode begin--> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.0</version> </dependency> <!--qrcode end-->
導入zxing庫供生成qrcode使用
四,java代碼說明
1,QrCodeUtil.java
/** * 二維碼工具類 * by liuhongdi */ public class QrCodeUtil { //編碼格式,采用utf-8 private static final String UNICODE = "utf-8"; //圖片格式 private static final String FORMAT = "JPG"; //二維碼寬度像素pixels數量 private static final int QRCODE_WIDTH = 300; //二維碼高度像素pixels數量 private static final int QRCODE_HEIGHT = 300; //LOGO寬度像素pixels數量 private static final int LOGO_WIDTH = 100; //LOGO高度像素pixels數量 private static final int LOGO_HEIGHT = 100; //生成二維碼圖片 //content 二維碼內容 //logoPath logo圖片地址 private static BufferedImage createImage(String content, String logoPath) throws Exception { Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, UNICODE); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (logoPath == null || "".equals(logoPath)) { return image; } // 插入圖片 QrCodeUtil.insertImage(image, logoPath); return image; } //在圖片上插入LOGO //source 二維碼圖片內容 //logoPath LOGO圖片地址 private static void insertImage(BufferedImage source, String logoPath) throws Exception { File file = new File(logoPath); if (!file.exists()) { throw new Exception("logo file not found."); } Image src = ImageIO.read(new File(logoPath)); int width = src.getWidth(null); int height = src.getHeight(null); if (width > LOGO_WIDTH) { width = LOGO_WIDTH; } if (height > LOGO_HEIGHT) { height = LOGO_HEIGHT; } Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(image, 0, 0, null); // 繪制縮小后的圖 g.dispose(); src = image; // 插入LOGO Graphics2D graph = source.createGraphics(); int x = (QRCODE_WIDTH - width) / 2; int y = (QRCODE_HEIGHT - height) / 2; graph.drawImage(src, x, y, width, height, null); Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6); graph.setStroke(new BasicStroke(3f)); graph.draw(shape); graph.dispose(); } //生成帶logo的二維碼圖片,保存到指定的路徑 // content 二維碼內容 // logoPath logo圖片地址 // destPath 生成圖片的存儲路徑 public static String save(String content, String logoPath, String destPath) throws Exception { BufferedImage image = QrCodeUtil.createImage(content, logoPath); File file = new File(destPath); String path = file.getAbsolutePath(); File filePath = new File(path); if (!filePath.exists() && !filePath.isDirectory()) { filePath.mkdirs(); } String fileName = file.getName(); fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length()) + "." + FORMAT.toLowerCase(); System.out.println("destPath:"+destPath); ImageIO.write(image, FORMAT, new File(destPath)); return fileName; } //生成二維碼圖片,直接輸出到OutputStream public static void encode(String content, String logoPath, OutputStream output) throws Exception { BufferedImage image = QrCodeUtil.createImage(content, logoPath); ImageIO.write(image, FORMAT, output); } //解析二維碼圖片,得到包含的內容 public static String decode(String path) throws Exception { File file = new File(path); BufferedImage image = ImageIO.read(file); if (image == null) { return null; } BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(); hints.put(DecodeHintType.CHARACTER_SET, UNICODE); result = new MultiFormatReader().decode(bitmap, hints); return result.getText(); } }
工具類,包含了生成二維碼、保存二維碼,展示二維碼,解析二維碼
2,HomeController.java
@RequestMapping("/home") @Controller public class HomeController { //生成帶logo的二維碼到response @RequestMapping("/qrcode") public void qrcode(HttpServletRequest request, HttpServletResponse response) { String requestUrl = "http://www.baidu.com"; try { OutputStream os = response.getOutputStream(); QrCodeUtil.encode(requestUrl, "/data/springboot2/logo.jpg", os); } catch (Exception e) { e.printStackTrace(); } } //生成不帶logo的二維碼到response @RequestMapping("/qrnologo") public void qrnologo(HttpServletRequest request, HttpServletResponse response) { String requestUrl = "http://www.baidu.com"; try { OutputStream os = response.getOutputStream(); QrCodeUtil.encode(requestUrl, null, os); } catch (Exception e) { e.printStackTrace(); } } //把二維碼保存成文件 @RequestMapping("/qrsave") @ResponseBody public String qrsave() { String requestUrl = "http://www.baidu.com"; try { QrCodeUtil.save(requestUrl, "/data/springboot2/logo.jpg", "/data/springboot2/qrcode2.jpg"); } catch (Exception e) { e.printStackTrace(); } return "文件已保存"; } //解析二維碼中的文字 @RequestMapping("/qrtext") @ResponseBody public String qrtext() { String url = ""; try { url = QrCodeUtil.decode("/data/springboot2/qrcode2.jpg"); } catch (Exception e) { e.printStackTrace(); } return "解析到的url:"+url; } }
入口處包含了四個方法,接下來我們做測試
五,測試效果
1,生成不帶logo的二維碼,訪問:
http://127.0.0.1:8080/home/qrnologo
效果:
2,生成帶logo的二維碼:訪問
http://127.0.0.1:8080/home/qrcode
效果:
3,生成二維碼保存成文件:訪問:
http://127.0.0.1:8080/home/qrsave
代碼中文件被保存成了:/data/springboot2/qrcode2.jpg
4,解析二維碼中包含的文字信息:訪問:
http://127.0.0.1:8080/home/qrtext
返回:
解析到的url:http://www.baidu.com
成功解析到了圖片中包含的url地址
六,查看spring boot版本
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.2.RELEASE)