二维码的生成方式(java)

介绍三种二维码的生成方式:

  第一种:使用google的zxing生成

[java]  view plain  copy
  1. package com.zxing;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4. import java.io.File;  
  5. import java.io.IOException;  
  6. import java.nio.file.FileSystems;  
  7. import java.nio.file.Path;  
  8. import java.util.HashMap;  
  9. import java.util.Map;  
  10.   
  11. import javax.imageio.ImageIO;  
  12.   
  13. import com.google.zxing.BarcodeFormat;  
  14. import com.google.zxing.Binarizer;  
  15. import com.google.zxing.BinaryBitmap;  
  16. import com.google.zxing.DecodeHintType;  
  17. import com.google.zxing.EncodeHintType;  
  18. import com.google.zxing.LuminanceSource;  
  19. import com.google.zxing.MultiFormatReader;  
  20. import com.google.zxing.MultiFormatWriter;  
  21. import com.google.zxing.NotFoundException;  
  22. import com.google.zxing.Result;  
  23. import com.google.zxing.WriterException;  
  24. import com.google.zxing.client.j2se.BufferedImageLuminanceSource;  
  25. import com.google.zxing.client.j2se.MatrixToImageWriter;  
  26. import com.google.zxing.common.BitMatrix;  
  27. import com.google.zxing.common.HybridBinarizer;  
  28.   
  29. public class TestZXing {  
  30.   
  31.     public static void main(String[] args) throws Exception {  
  32.         // testEncode();  
  33.         testDecode();  
  34.     }  
  35.   
  36.     /** 
  37.      * 生成二维码 
  38.      *  
  39.      * @throws WriterException 
  40.      * @throws IOException 
  41.      */  
  42.     public static void testEncode() throws WriterException, IOException {  
  43.         String filePath = "D://";  
  44.         String fileName = "zxing.png";  
  45.         String content = "测试zxing生成二维码";  
  46.         int width = 300// 图像宽度  
  47.         int height = 300// 图像高度  
  48.         String format = "png";// 图像类型  
  49.         Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
  50.         hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
  51.         BitMatrix bitMatrix = new MultiFormatWriter().encode(content,  
  52.                 BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵  
  53.         Path path = FileSystems.getDefault().getPath(filePath, fileName);  
  54.         MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像  
  55.         System.out.println("输出成功.");  
  56.     }  
  57.   
  58.     /** 
  59.      * 解析二维码 
  60.      */  
  61.     public static void testDecode() {  
  62.         String filePath = "D://zxing.png";  
  63.         BufferedImage image;  
  64.         try {  
  65.             image = ImageIO.read(new File(filePath));  
  66.             LuminanceSource source = new BufferedImageLuminanceSource(image);  
  67.             Binarizer binarizer = new HybridBinarizer(source);  
  68.             BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);  
  69.             Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();  
  70.             hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");  
  71.             Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码  
  72.             System.out.println("图片中内容:  ");  
  73.             System.out.println("author: " + result.getText());  
  74.             System.out.println("图片中格式:  ");  
  75.             System.out.println("encode: " + result.getBarcodeFormat());  
  76.         } catch (IOException e) {  
  77.             e.printStackTrace();  
  78.         } catch (NotFoundException e) {  
  79.             e.printStackTrace();  
  80.         }  
  81.     }  
  82.   
  83. }  

第二种方式:使用qrCode方式

[java]  view plain  copy
  1. package com.qrCode;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Graphics2D;  
  5. import java.awt.image.BufferedImage;  
  6. import java.io.File;  
  7. import java.io.IOException;  
  8. import javax.imageio.ImageIO;  
  9. import com.swetake.util.Qrcode;  
  10. import jp.sourceforge.qrcode.QRCodeDecoder;  
  11. import jp.sourceforge.qrcode.exception.DecodingFailedException;  
  12.   
  13. public class QRCode {  
  14.   
  15.     /** 
  16.      * 解析二维码(QRCode) 
  17.      *  
  18.      * @param imgPath 
  19.      * @return 
  20.      */  
  21.     public static String decoderQRCode(String imgPath) {  
  22.         // QRCode 二维码图片的文件  
  23.         File imageFile = new File(imgPath);  
  24.         BufferedImage bufImg = null;  
  25.         String content = null;  
  26.         try {  
  27.             bufImg = ImageIO.read(imageFile);  
  28.             QRCodeDecoder decoder = new QRCodeDecoder();  
  29.             content = new String(decoder.decode(new QRCodeImageBean(bufImg)), "utf-8");  
  30.         } catch (IOException e) {  
  31.             System.out.println("Error: " + e.getMessage());  
  32.             e.printStackTrace();  
  33.         } catch (DecodingFailedException dfe) {  
  34.             System.out.println("Error: " + dfe.getMessage());  
  35.             dfe.printStackTrace();  
  36.         }  
  37.         return content;  
  38.     }  
  39.   
  40.     /** 
  41.      * 生成二维码(QRCode)图片 
  42.      *  
  43.      * @param content  存储内容 
  44.      * @param imgPath 图片路径 
  45.      * @param imgType  图片类型 
  46.      */  
  47.     public static void encoderQRCode(String content, String imgPath, String imgType) {  
  48.         encoderQRCode(content, imgPath, imgType, 7);  
  49.     }  
  50.   
  51.     /** 
  52.      * 生成二维码(QRCode)图片 
  53.      *  
  54.      * @param content   存储内容 
  55.      * @param imgPath  图片路径 
  56.      * @param imgType 图片类型 
  57.      * @param size 二维码尺寸 
  58.      */  
  59.     public static void encoderQRCode(String content, String imgPath, String imgType, int size) {  
  60.         try {  
  61.             BufferedImage bufImg = qRCodeCommon(content, imgType, size);  
  62.             File imgFile = new File(imgPath);  
  63.             // 生成二维码QRCode图片  
  64.             ImageIO.write(bufImg, imgType, imgFile);  
  65.         } catch (Exception e) {  
  66.             e.printStackTrace();  
  67.         }  
  68.     }  
  69.   
  70.     /** 
  71.      * 生成二维码(QRCode)图片的公共方法 
  72.      *  
  73.      * @param content  存储内容 
  74.      * @param imgType 图片类型 
  75.      * @param size 二维码尺寸(1-40) 
  76.      * @return 
  77.      */  
  78.     private static BufferedImage qRCodeCommon(String content, String imgType, int size) {  
  79.         BufferedImage bufImg = null;  
  80.         try {  
  81.             Qrcode qrcodeHandler = new Qrcode();  
  82.             // 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小  
  83.             qrcodeHandler.setQrcodeErrorCorrect('M');  
  84.             qrcodeHandler.setQrcodeEncodeMode('B');  
  85.             // 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大  
  86.             qrcodeHandler.setQrcodeVersion(size);  
  87.             // 获得内容的字节数组,设置编码格式  
  88.             byte[] contentBytes = content.getBytes("utf-8");  
  89.             // 图片尺寸  
  90.             int imgSize = 67 + 12 * (size - 1);  
  91.             bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);  
  92.             Graphics2D gs = bufImg.createGraphics();  
  93.             // 设置背景颜色  
  94.             gs.setBackground(Color.WHITE);  
  95.             gs.clearRect(00, imgSize, imgSize);  
  96.   
  97.             // 设定图像颜色> BLACK  
  98.             gs.setColor(Color.BLACK);  
  99.             // 设置偏移量,不设置可能导致解析出错  
  100.             int pixoff = 2;  
  101.             // 输出内容> 二维码  
  102.             if (contentBytes.length > 0 && contentBytes.length < 800) {  
  103.                 boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);  
  104.                 for (int i = 0; i < codeOut.length; i++) {  
  105.                     for (int j = 0; j < codeOut.length; j++) {  
  106.                         if (codeOut[j][i]) {  
  107.                             gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 33);  
  108.                         }  
  109.                     }  
  110.                 }  
  111.             } else {  
  112.                 throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");  
  113.             }  
  114.             gs.dispose();  
  115.             bufImg.flush();  
  116.         } catch (Exception e) {  
  117.             e.printStackTrace();  
  118.         }  
  119.         return bufImg;  
  120.     }  
  121.   
  122. }  
[java]  view plain  copy
  1. package com.qrCode;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4. import jp.sourceforge.qrcode.data.QRCodeImage;  
  5.   
  6. public class QRCodeImageBean implements QRCodeImage {  
  7.   
  8.     BufferedImage bufImg;    
  9.       
  10.     public QRCodeImageBean(BufferedImage bufImg) {    
  11.         this.bufImg = bufImg;    
  12.     }    
  13.     public int getHeight() {    
  14.         return bufImg.getHeight();    
  15.     }    
  16.     public int getPixel(int x, int y) {    
  17.         return bufImg.getRGB(x, y);    
  18.     }    
  19.     public int getWidth() {    
  20.         return bufImg.getWidth();    
  21.     }    
  22. }  

[java]  view plain  copy
  1. package com.qrCode;  
  2.   
  3. public class TestQRCode {  
  4.   
  5.     public static void main(String[] args) {  
  6.            
  7.         //生成二维码  
  8.          String imgPath = "d:/qrCode.png";  
  9.          String encoderContent = "http://www.qrCode.com";  
  10.          QRCode.encoderQRCode(encoderContent, imgPath, "png");  
  11.          System.out.println("encoder success!!!");  
  12.            
  13.          //解析二维码  
  14.          String imgPath2 = "d:/qrCode.png";  
  15.          String qrCon = QRCode.decoderQRCode(imgPath2);  
  16.          System.out.println("decoder success!!!");  
  17.          System.out.println("二维码内容为:" + qrCon);  
  18.     }  
  19. }  

第三种方式:这也是最简单的方式使用jQuery的qrCode插件

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>使用JQueryQrCode生成二维码</title>  
  6. <script type="text/javascript" src="./js/jquery-1.9.1.min.js"></script>  
  7. <script type="text/javascript" src="./js/qrcode.js"></script>  
  8. </head>  
  9. <body>  
  10. <div id="qrcode"></div>  
  11.   
  12. <script type="text/javascript">  
  13. //参数1表示图像大小,取值范围1-10;参数2表示质量,取值范围'L','M','Q','H'  
  14. var content = "使用JQueryQrCode生成二维码"  
  15. var qr = qrcode(8, 'M');  
  16. qr.addData(content);  
  17. qr.make();  
  18. /* var dom=document.createElement('DIV');  
  19. dom.innerHTML = qr.createImgTag();  
  20. var element=document.getElementById("qrcode");  
  21. element.appendChild(dom); */  
  22. $("#qrcode").html(qr.createImgTag());  
  23.     
  24. </script>  
  25. </body>  
  26. </html>  

猜你喜欢

转载自blog.csdn.net/awj321000/article/details/78912351