java生成二維碼,讀取(解析)二維碼圖片


二維碼分為好多種,我們最常用的是qrcode類型的二維碼,以下有三種生成方式以及解析方式:

附所需jar包或者js地址

第一種:依賴qrcode.jar


   
   
  
  
          
  1. import java.awt.Color;
  2. import java.awt.Graphics2D;
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.UnsupportedEncodingException;
  6. import javax.imageio.ImageIO;
  7. import com.swetake.util.Qrcode;
  8. /**獲取qrcode jar包 https://osdn.jp/projects/qrcode
  9. * 生成qrcode二維碼
  10. * @author fangyi
  11. *
  12. */
  13. public class CreateQrCode {
  14. public static void main(String[] args) throws Exception {
  15. Qrcode qrcode= new Qrcode();
  16. qrcode.setQrcodeErrorCorrect( 'M'); //糾錯等級
  17. qrcode.setQrcodeEncodeMode( 'B'); //N代表數字 A代表字母 B代表其他
  18. qrcode.setQrcodeVersion( 7); //版本
  19. String qrData = "www.baidu.com"; //二維碼信息內容
  20. int width= 67+ 12*( 7- 1);
  21. int height= 67+ 12*( 7- 1);
  22. BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  23. //畫圖工具
  24. Graphics2D gs= bufferedImage.createGraphics();
  25. //設置屬性
  26. gs.setBackground(Color.WHITE);
  27. gs.setColor(Color.BLACK);
  28. gs.clearRect( 0, 0, width, height);
  29. //填充
  30. int pixoff= 2; //偏移量
  31. byte[] d = qrData.getBytes( "gb2312"); //編碼防止有中文
  32. if ( 0 < d.length && d.length< 120) {
  33. boolean[][] s = qrcode.calQrcode(d);
  34. for ( int i = 0; i < s.length; i++) {
  35. for ( int j = 0; j < s.length; j++) {
  36. if(s[j][i]){
  37. gs.fillRect(i* 3+pixoff, j* 3+pixoff, 3, 3);
  38. }
  39. }
  40. }
  41. }
  42. //關閉資源,並保存文件
  43. gs.dispose();
  44. bufferedImage.flush();
  45. ImageIO.write(bufferedImage, "png", new File( "D:/qrcode.jpg")); //輸出到指定地方
  46. }
  47. }
 讀取指定的二維碼:

 


   
   
  
  
          
  1. import java.awt.image.BufferedImage;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import javax.imageio.ImageIO;
  5. import jp.sourceforge.qrcode.QRCodeDecoder;
  6. /**
  7. * 讀取制定路徑下的qrcode信息
  8. * @author fangyi
  9. *
  10. */
  11. public class ReaderQrcode {
  12. public static void main(String[] args) throws IOException {
  13. //指定的二維碼文件路徑
  14. File file= new File( "D:/jqueryqrcode.png");
  15. BufferedImage bufferedImage = ImageIO.read(file);
  16. QRCodeDecoder qrCodeDecoder = new QRCodeDecoder();
  17. String result = new String(qrCodeDecoder.decode( new MyQRCodeImage(bufferedImage)), "gb2312");
  18. //輸出結果
  19. System.out.println(result);
  20. bufferedImage.flush();
  21. }
  22. }
  23. import java.awt.image.BufferedImage;
  24. import jp.sourceforge.qrcode.data.QRCodeImage;
  25. /**
  26. * 自定義QRCodeImage類實現QRCodeImage 供讀取時所用
  27. * @author fangyi
  28. *
  29. */
  30. public class MyQRCodeImage implements QRCodeImage {
  31. BufferedImage bufferedImage ;
  32. public MyQRCodeImage(BufferedImage bufferedImage) {
  33. super();
  34. this.bufferedImage = bufferedImage;
  35. }
  36. @Override
  37. public int getHeight() {
  38. return bufferedImage.getHeight();
  39. }
  40. @Override
  41. public int getPixel(int arg0, int arg1) {
  42. return bufferedImage.getRGB(arg0, arg1);
  43. }
  44. @Override
  45. public int getWidth() {
  46. return bufferedImage.getWidth();
  47. }
  48. }
第二種:創建動態的web工程 依賴jquery.qrcode.min.js   jquery.js  運行工程訪問下面jsp就可以了

    


   
   
  
  
          
  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. <!-- js地址https://github.com/jeromeetienne/jquery-qrcode -->
  9. <script type="text/javascript" src=" <%=request.getContextPath() %> /js/jquery.min.js"></script>
  10. <script type="text/javascript" src=" <%=request.getContextPath() %> /js/jquery.qrcode.min.js"></script>
  11. </head>
  12. <body>
  13. 生成二維碼如下: <br> <br> <br>
  14. <div id="qrcode"> </div>
  15. <script type="text/javascript">
  16. $( '#qrcode' ).qrcode( "www.baidu.com" ); //生產二維碼
  17. /* jquery('#qrcode').qrcode({width: 64,height: 64,text: "size doesn't matter"}); */
  18. </script>
  19. </body>
  20. </html>
第三種 創建Java project  依賴zxing3.2.1.jar

  


   
   
  
  
          
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.util.Hashtable;
  4. import com.google.zxing.BarcodeFormat;
  5. import com.google.zxing.EncodeHintType;
  6. import com.google.zxing.MultiFormatWriter;
  7. import com.google.zxing.WriterException;
  8. import com.google.zxing.common.BitMatrix;
  9. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  10. /**
  11. * zxing jar包地址 https://github.com/Candy1575/QRcode
  12. * 依賴MatrixToImageWriter類
  13. * @author fangyi
  14. *
  15. */
  16. public class EncodeTest {
  17. public static void Encode_QR_CODE() throws IOException, WriterException{
  18. String contents = "ZXing 二維碼內容1234!"; // 二維碼內容
  19. int width = 430; // 二維碼圖片寬度 300
  20. int height = 430; // 二維碼圖片高度300
  21. String format = "gif"; // 二維碼的圖片格式 gif
  22. Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
  23. // 指定糾錯等級,糾錯級別(L 7%、M 15%、Q 25%、H 30%)
  24. hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
  25. // 內容所使用字符集編碼
  26. hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
  27. // hints.put(EncodeHintType.MAX_SIZE, 350);//設置圖片的最大值
  28. // hints.put(EncodeHintType.MIN_SIZE, 100);//設置圖片的最小值
  29. hints.put(EncodeHintType.MARGIN, 1); //設置二維碼邊的空度,非負數
  30. BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, //要編碼的內容
  31. //編碼類型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
  32. //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
  33. //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
  34. BarcodeFormat.QR_CODE,
  35. width, //條形碼的寬度
  36. height, //條形碼的高度
  37. hints); //生成條形碼時的一些配置,此項可選
  38. // 生成二維碼
  39. File outputFile = new File( "D:" + File.separator + "mycode.gif"); //指定輸出路徑
  40. MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
  41. }
  42. public static void main(String[] args) throws Exception {
  43. try {
  44. Encode_QR_CODE();
  45. } catch (Exception e) {
  46. // TODO: handle exception
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. import java.awt.image.BufferedImage;
  52. import java.io.File;
  53. import java.io.IOException;
  54. import java.io.OutputStream;
  55. import javax.imageio.ImageIO;
  56. import com.google.zxing.common.BitMatrix;
  57. /**
  58. * 二維碼的生成需要借助MatrixToImageWriter類,
  59. * 該類是由Google提供的,可以將該類直接拷貝到源碼中使用,當然你也可以自己寫個
  60. * 生產條形碼的基類 依賴LogoConfig類
  61. */
  62. public class MatrixToImageWriter {
  63. private static final int BLACK = 0xFF000000; //用於設置圖案的顏色
  64. private static final int WHITE = 0xFFFFFFFF; //用於背景色
  65. private MatrixToImageWriter() {
  66. }
  67. public static BufferedImage toBufferedImage(BitMatrix matrix) {
  68. int width = matrix.getWidth();
  69. int height = matrix.getHeight();
  70. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  71. for ( int x = 0; x < width; x++) {
  72. for ( int y = 0; y < height; y++) {
  73. image.setRGB(x, y, (matrix.get(x, y) ? BLACK : WHITE));
  74. // image.setRGB(x, y, (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
  75. }
  76. }
  77. return image;
  78. }
  79. public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
  80. BufferedImage image = toBufferedImage(matrix);
  81. //設置logo圖標
  82. LogoConfig logoConfig = new LogoConfig();
  83. image = logoConfig.LogoMatrix(image);
  84. if (!ImageIO.write(image, format, file)) {
  85. throw new IOException( "Could not write an image of format " + format + " to " + file);
  86. } else{
  87. System.out.println( "圖片生成成功!");
  88. }
  89. }
  90. public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
  91. BufferedImage image = toBufferedImage(matrix);
  92. //設置logo圖標
  93. LogoConfig logoConfig = new LogoConfig();
  94. image = logoConfig.LogoMatrix(image);
  95. if (!ImageIO.write(image, format, stream)) {
  96. throw new IOException( "Could not write an image of format " + format);
  97. }
  98. }
  99. }
  100. import java.awt.BasicStroke;
  101. import java.awt.Color;
  102. import java.awt.Graphics2D;
  103. import java.awt.geom.RoundRectangle2D;
  104. import java.awt.image.BufferedImage;
  105. import java.io.File;
  106. import java.io.IOException;
  107. import javax.imageio.ImageIO;
  108. /**
  109. * 二維碼 添加自定義 logo圖標 處理的方法,
  110. * 模仿微信自動生成二維碼效果,有圓角邊框,logo和二維碼間有空白區,logo帶有灰色邊框
  111. * @author fangyi
  112. *
  113. */
  114. public class LogoConfig {
  115. /**
  116. * 設置 logo
  117. * @param matrixImage 源二維碼圖片
  118. * @return 返回帶有logo的二維碼圖片
  119. * @throws IOException
  120. * @author Administrator sangwenhao
  121. */
  122. public BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException{
  123. /**
  124. * 讀取二維碼圖片,並構建繪圖對象
  125. */
  126. Graphics2D g2 = matrixImage.createGraphics();
  127. int matrixWidth = matrixImage.getWidth();
  128. int matrixHeigh = matrixImage.getHeight();
  129. /**
  130. * 讀取Logo圖片
  131. */
  132. BufferedImage logo = ImageIO.read( new File( "C:\\Users\\fangyi\\Pictures\\code-wallpaper-18.png"));
  133. //開始繪制圖片
  134. g2.drawImage(logo,matrixWidth/ 5* 2,matrixHeigh/ 5* 2, matrixWidth/ 5, matrixHeigh/ 5, null); //繪制
  135. BasicStroke stroke = new BasicStroke( 5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
  136. g2.setStroke(stroke); // 設置筆畫對象
  137. //指定弧度的圓角矩形
  138. RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/ 5* 2, matrixHeigh/ 5* 2, matrixWidth/ 5, matrixHeigh/ 5, 20, 20);
  139. g2.setColor(Color.white);
  140. g2.draw(round); // 繪制圓弧矩形
  141. //設置logo 有一道灰色邊框
  142. BasicStroke stroke2 = new BasicStroke( 1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
  143. g2.setStroke(stroke2); // 設置筆畫對象
  144. RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/ 5* 2+ 2, matrixHeigh/ 5* 2+ 2, matrixWidth/ 5- 4, matrixHeigh/ 5- 4, 20, 20);
  145. g2.setColor( new Color( 128, 128, 128));
  146. g2.draw(round2); // 繪制圓弧矩形
  147. g2.dispose();
  148. matrixImage.flush() ;
  149. return matrixImage ;
  150. }
  151. }
讀取二維碼信息

  


   
   
  
  
          
  1. import java.awt.image.BufferedImage;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import java.util.Map;
  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.NotFoundException;
  13. import com.google.zxing.Result;
  14. import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
  15. import com.google.zxing.common.BitArray;
  16. import com.google.zxing.common.BitMatrix;
  17. import com.google.zxing.common.HybridBinarizer;
  18. /**
  19. * 讀取zxing類型下的二維碼信息
  20. * @author fangyi
  21. *
  22. */
  23. public class ReadQrCode_Zxing {
  24. @SuppressWarnings( "unchecked")
  25. public static void main(String[] args) {
  26. try {
  27. MultiFormatReader formatReader = new MultiFormatReader();
  28. //讀取指定的二維碼文件
  29. File file= new File( "D:\\mycode.gif");
  30. BufferedImage bufferedImage =ImageIO.read(file);
  31. BinaryBitmap binaryBitmap= new BinaryBitmap( new HybridBinarizer( new BufferedImageLuminanceSource(bufferedImage)));
  32. //定義二維碼參數
  33. Map hints= new HashMap<>();
  34. hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
  35. Result result = formatReader.decode(binaryBitmap, hints);
  36. //輸出相關的二維碼信息
  37. System.out.println( "解析結果"+result.toString());
  38. System.out.println( "二維碼格式類型"+result.getBarcodeFormat());
  39. System.out.println( "二維碼文本內容"+result.getText());
  40. bufferedImage.flush();
  41. } catch (NotFoundException e) {
  42. e.printStackTrace();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. }

  用二維碼進行添加好友獲取好友信息是用到VCard

 微信掃碼登陸網頁原理:通過堵塞等待的長連接,近乎實時的獲得信息。 對於驗證過程,Open API 一般是通過授權令牌(Token)來解決的,原理是當用戶通過授權后,分配一個限定條件下的令牌(如限制本機訪問、限制授權有效時間、限制同時登錄設備數等),使獲得授權的用戶僅在有限的前提下能訪問相關服務。 像計算機休眠后曾做的授權就自動收回了,這樣就有效的避免了在別人電腦上(尤其是網吧)打開,但忘記關閉或退出這類安全問題了。

實現可借鑒已有博客:https://www.cnblogs.com/zijun/p/3580125.html




免責聲明!

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



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