你不可錯過的二維碼生成與解析-java后台與前端js都有


1.二維碼分類

  二維條碼也有許多不同的碼制,就碼制的編碼原理而言,通常分為三種類型。

  1. 線性堆疊式二維碼

編碼原理:
建立在一維條碼基礎之上,按需要堆積成兩行或多行。

圖示:
image

  1. 矩陣式二維碼

最常用編碼,原理:
在一個矩形空間通過黑白像素在矩陣中的不同分布進行編碼。在矩陣相應的位置上,用點(方點、圓點或其它形狀)的出現表示二進制“1”,點的不出現表示二進制的“0”

圖示:
image

  1. 郵政碼

    通過不同長度的條進行編碼,主要用於郵政編碼。

2.QR Code

  現在最常用的就是這種,咱們現在主要介紹的也是這種。為啥這種使用二維碼那么受反應呢?主要QR Code這種二維碼有如下優點:

  1. 識讀速度快
  2. 數據密度大
  3. 占用空間小

2.1 QR Code介紹

image

2.2 QR Code 結構

image
大家可以了解下二維碼的結構,知道大概就行了,如果想了解詳細信息的話可以自行百度,國家有詳細的二維碼規范。

3.后台JAVA代碼實現二維碼(QR Code)生成

  這里介紹如下兩種實現方式:

  1. Java 后台實現,主要使用zxing和qrcodejar等第三方jar包。
  2. 前端javascript實現,主要使用jquery.qrcode.js

3.1 使用zxing生成二維碼

3.1.1 zxing相關網站

zxing的GitHub
zxing的Java文檔

3.1.2 生成zxing jar包

由於github上沒有相關的jar包,所以需要我們自己生成一下,上面有好多關於android相關的,我們只需要選取核心包和javase這兩部分代碼。既下圖矩形框內容:
image
生成方式我大致說下:首先在ecplise里新建一個java項目zxing,將剛才畫框代碼拷貝進去,然后導出jar包即可。如果你不想生成也可以在我的github上自行下載。

3.1.3 生成二維碼代碼


   
   
  
  
          
  1. package cn.rivamed.zxing;
  2. import java.io.File;
  3. import java.nio.file.Path;
  4. import java.util.HashMap;
  5. import com.google.zxing.BarcodeFormat;
  6. import com.google.zxing.EncodeHintType;
  7. import com.google.zxing.MultiFormatWriter;
  8. import com.google.zxing.client.j2se.MatrixToImageWriter;
  9. import com.google.zxing.common.BitMatrix;
  10. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  11. public class CreateQRCode {
  12. public static void main( String[] args) {
  13. int width= 300;
  14. int height= 300;
  15. String format= "png";
  16. //這里如果你想自動跳轉的話,需要加上https://
  17. String content= "https://github.com/hbbliyong/QRCode.git";
  18. HashMap hits=new HashMap();
  19. hits.put( EncodeHintType. CHARACTER_SET, "utf-8"); //編碼
  20. //糾錯等級,糾錯等級越高存儲信息越少
  21. hits.put( EncodeHintType. ERROR_CORRECTION, ErrorCorrectionLevel. M);
  22. //邊距
  23. hits.put( EncodeHintType. MARGIN, 2);
  24. try {
  25. BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat. QR_CODE, width, height,hits);
  26. //如果做網頁版輸出可以用輸出到流
  27. //MatrixToImageWriter.writeToStream(matrix, format, stream);
  28. Path path=new File( "D:/zxingQRCode.png").toPath();
  29. MatrixToImageWriter.writeToPath(bitMatrix, format, path);
  30. } catch ( Exception e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. }
  34. System.out. println( "that is all");
  35. }
  36. }

生成的結果如下:
image

由於代碼都有詳細注釋,我就不一一講解了,有疑問可以留言,我們一塊探討。

3.1.4 解析二維碼代碼


   
   
  
  
          
  1. package cn.rivamed.zxing;
  2. import java.awt.image.BufferedImage;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.util.HashMap;
  6. import javax.imageio.ImageIO;
  7. import com.google.zxing.Binarizer;
  8. import com.google.zxing.BinaryBitmap;
  9. import com.google.zxing.EncodeHintType;
  10. import com.google.zxing.LuminanceSource;
  11. import com.google.zxing.MultiFormatReader;
  12. import com.google.zxing.MultiFormatWriter;
  13. import com.google.zxing.NotFoundException;
  14. import com.google.zxing.Result;
  15. import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
  16. import com.google.zxing.common.BitArray;
  17. import com.google.zxing.common.BitMatrix;
  18. import com.google.zxing.common.HybridBinarizer;
  19. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  20. public class ReadQRCode {
  21. public static void main( String[] args) {
  22. try {
  23. MultiFormatReader formatReader=new MultiFormatReader();
  24. File file=new File( "D:/zxingQRCode.png");
  25. BufferedImage image= ImageIO.read(file);
  26. BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
  27. HashMap hints=new HashMap();
  28. hints.put( EncodeHintType. CHARACTER_SET, "utf-8"); //編碼
  29. Result result=formatReader.decode(binaryBitmap, hints);
  30. System.out. println( "解析結果:"+result. toString());
  31. System.out. println( "二維碼格式類型:"+result.getBarcodeFormat());
  32. System.out. println( "二維碼文本"+result.getText());
  33. } catch ( Exception e) {
  34. // TODO Auto-generated catch block
  35. e.printStackTrace();
  36. }
  37. }
  38. }

3.2 使用qrcode生成解析二維碼

3.2.1 生成二維碼


   
   
  
  
          
  1. package cn.rivamed.qrcode;
  2. import java.awt.Color;
  3. import java.awt.Graphics2D;
  4. import java.awt.image.BufferedImage;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import java.io.UnsupportedEncodingException;
  8. import javax.imageio.ImageIO;
  9. import com.swetake.util.Qrcode;
  10. public class CreateQRCode {
  11. public static void main(String[] args) throws IOException {
  12. Qrcode x= new Qrcode();
  13. int version= 7;
  14. x.setQrcodeErrorCorrect( 'M'); //糾錯等級
  15. x.setQrcodeEncodeMode( 'B'); //N代表數字,A代表a-Z,B代表其它(中文等)
  16. x.setQrcodeVersion(version); //版本號
  17. String qrData= "https://github.com/hbbliyong/QRCode.git";
  18. //int width=300;
  19. int width= 67+ 12*(version- 1);
  20. //int height=300;
  21. int height= 67+ 12*(version- 1);
  22. BufferedImage bufferedImage= new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  23. Graphics2D gs=bufferedImage.createGraphics();
  24. gs.setBackground(Color.WHITE);
  25. gs.setColor(Color.BLACK);
  26. gs.clearRect( 0, 0, width, height);
  27. int pixoff= 2; //偏移量,如果不加有可能會導致識別不准確
  28. //如果有漢字需要加上編碼
  29. byte[] d=qrData.getBytes( "gb2312");
  30. //byte[] d=qrData.getBytes();
  31. if(d.length> 0&&d.length< 120){
  32. boolean[][] s=x.calQrcode(d);
  33. for( int i= 0;i<s.length;i++){
  34. for( int j= 0;j<s.length;j++){
  35. if(s[j][i]){
  36. gs.fillRect(j* 3+pixoff, i* 3+pixoff, 3, 3);
  37. }
  38. }
  39. }
  40. }
  41. gs.dispose();
  42. bufferedImage.flush();
  43. ImageIO.write(bufferedImage, "png", new File( "D:/qrcode.png"));
  44. }
  45. }

生成的結果如下:

image

這里需要注意的是,二維碼長寬不能想zxing之直接定義,需要跟進這個公式生成67+12*(version-1)。比如我直接定義二維碼的長寬為300.就會變成如下樣子。
image這上面空白看的不是太清,你把圖片下載下載下來看就比較明顯了。

3.2.2 解析二維碼


   
   
  
  
          
  1. package cn.rivamed.qrcode;
  2. import java.awt.image.BufferedImage;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import javax.imageio.ImageIO;
  6. import jp.sourceforge.qrcode.QRCodeDecoder;
  7. import jp.sourceforge.qrcode.data.QRCodeImage;
  8. public class ReadQRCode {
  9. public static void main(String[] args) throws IOException {
  10. File file= new File( "D:/qrcode.png");
  11. BufferedImage bufferedImage=ImageIO.read(file);
  12. QRCodeDecoder codeDecoder= new QRCodeDecoder();
  13. String result= new String(codeDecoder.decode( new QRCodeImage() {
  14. @Override
  15. public int getWidth() {
  16. // TODO Auto-generated method stub
  17. return bufferedImage.getWidth();
  18. }
  19. @Override
  20. public int getPixel(int arg0, int arg1) {
  21. // TODO Auto-generated method stub
  22. return bufferedImage.getRGB(arg0, arg1);
  23. }
  24. @Override
  25. public int getHeight() {
  26. // TODO Auto-generated method stub
  27. return bufferedImage.getHeight();
  28. }
  29. }), "gb2312");
  30. System.out.println(result);
  31. }
  32. }

4.前台代碼jquery生成二維碼

4.1 jquery.qrcode.js 的 GitHub

4.2 相關代碼


   
   
  
  
          
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding= "UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>二維碼生成 </title>
  8. <script type="text/javascript" src=" <%=request.getContextPath() %> /js/jquery.min.js"></script>
  9. <script type="text/javascript" src=" <%=request.getContextPath() %> /js/jquery.qrcode.min.js"></script>
  10. </head>
  11. <body>
  12. 生成的二維碼如下: <br>
  13. <dir id="qrcode"> </dir>
  14. <script type="text/javascript">
  15. jQuery( '#qrcode').qrcode( 'https://github.com/hbbliyong/QRCode.git');
  16. </script>
  17. </body>
  18. </html>

5.結束語

所有的代碼我都上傳到了github上面,大家可以下載運行。這里面介紹的都比較基礎的,但也包含了前端后台多種方式,對於簡單的應用已經足夠了。至於一些擴展,如果加上logo啊,電子名品啊,大家可以自行摸索。感謝您的觀看,如果有什么疑問可以留言。

ps:
一個在線生成二維碼的網站推薦:在線工具
這個工具也是使用的zxing


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM