免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1649 | 回复: 0
打印 上一主题 下一主题

ZXing 二维码编码&解码 [复制链接]

论坛徽章:
1
数据库技术版块每日发帖之星
日期:2015-07-11 22:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-14 09:53 |只看该作者 |倒序浏览
借助google.zxing生成二维码,需用到的jar
<dependencies>
    <dependency>
      <groupId>com.beust</groupId>
      <artifactId>jcommander</artifactId>
      <version>1.48</version>
    </dependency>
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>core</artifactId>
      <version>3.2.0</version>
  </dependency>
  <dependency>
    <groupId>com.google.zxing</groupId>
      <artifactId>javase</artifactId>
      <version>3.2.0</version>
  </dependency>
  </dependencies>


代码
  1. package web;

  2. import java.awt.AlphaComposite;
  3. import java.awt.Color;
  4. import java.awt.Graphics2D;
  5. import java.awt.RenderingHints;
  6. import java.awt.geom.RoundRectangle2D;
  7. import java.awt.image.BufferedImage;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.util.Hashtable;
  12. import java.util.Map;

  13. import javax.imageio.ImageIO;

  14. import com.google.zxing.BarcodeFormat;
  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.ReaderException;
  22. import com.google.zxing.Result;
  23. import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
  24. import com.google.zxing.client.j2se.MatrixToImageWriter;
  25. import com.google.zxing.common.BitMatrix;
  26. import com.google.zxing.common.HybridBinarizer;
  27. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

  28. /**
  29. * 二维码编码&解码
  30. * @Author: ChenGuiYong 2015年7月13日 上午11:09:56
  31. * @Version: $Id$
  32. * @Desc: <p></p>
  33. */
  34. public class QRCodeUtil {
  35.     private static final int BLACK = 0xFF000000;  
  36.     private static final int WHITE = 0xFFFFFFFF;
  37.     /*
  38.      * 解码:
  39.      * 1 将图片反解码为二维矩阵
  40.      * 2 将该二维矩阵解码为内容
  41.      * */
  42.     @SuppressWarnings({ "rawtypes", "unchecked" })
  43.     public static void decode(String imgPath) {  
  44.         try {  
  45.             File file = new File(imgPath);//获取该图片文件  
  46.             BufferedImage image;  
  47.             try {  
  48.                 image = ImageIO.read(file);  
  49.                 if (image == null) {  
  50.                     System.out.println("Could not decode image");  
  51.                 }  
  52.                 LuminanceSource source = new BufferedImageLuminanceSource(image);  
  53.                 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
  54.                 Result result;  
  55.                 Hashtable hints = new Hashtable();//将图片反解码为二维矩阵  
  56.                 hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");  
  57.                 result = new MultiFormatReader().decode(bitmap, hints);//将该二维矩阵解码成内容  
  58.                 String resultStr = result.getText();  
  59.                 System.out.println("解码结果:"+resultStr);  
  60.    
  61.             } catch (IOException ioe) {  
  62.                 System.out.println(ioe.toString());  
  63.             } catch (ReaderException re) {  
  64.                 System.out.println(re.toString());  
  65.             }  

  66.         } catch (Exception ex) {  
  67.             ex.printStackTrace();
  68.         }
  69.     }
  70.     /**
  71.      * 编码
  72.      * @author ChenGuiYong
  73.      * @data 2015年7月13日 上午11:06:20
  74.      * @param contents
  75.      * @param width
  76.      * @param height
  77.      * @param imgPath
  78.      * @param logoPath
  79.      * @return
  80.      */
  81.     public static boolean encode(String contents, int width, int height, String imgPath,String logoPath) {
  82.         Map<EncodeHintType, Object> hints = new Hashtable<>();
  83.         // 指定纠错等级
  84.         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
  85.         // 指定编码格式
  86.         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
  87.         //设置二维码内容到边框的距离
  88.         hints.put(EncodeHintType.MARGIN, 1);
  89.         String format = "png";
  90.         try {
  91.             BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
  92.             
  93.             MatrixToImageWriter.writeToStream(bitMatrix, format ,new FileOutputStream(imgPath));
  94.             
  95.             File qrcodeFile = new File(imgPath);
  96.             //增加logo
  97.             writeToLogo(bitMatrix,format , qrcodeFile, logoPath);  
  98.         } catch (Exception e) {
  99.             return false;
  100.         }
  101.         System.out.println("编码成功!");
  102.         return true;
  103.     }
  104.     /**
  105.      * 增加Logo
  106.      * @author ChenGuiYong
  107.      * @data 2015年7月13日 上午11:07:00
  108.      * @param matrix
  109.      * @param format
  110.      * @param file
  111.      * @param logoPath
  112.      * @throws IOException
  113.      */
  114.     public static void writeToLogo(BitMatrix matrix,String format,File file,String logoPath) throws IOException {
  115.         Graphics2D graphics2 = null;
  116.         BufferedImage image = null;
  117.         BufferedImage logo = null;
  118.         try {
  119.             /**
  120.              * 读取二维码图片,并构建绘图对象
  121.              */
  122.             image = toBufferedImage(matrix);  
  123.             graphics2 = image.createGraphics();  

  124.             /**
  125.              * 读取Logo图片
  126.              */
  127.             logo = ImageIO.read(new File(logoPath));  
  128.             int codeWidth = image.getWidth();
  129.             int codeHeight = image.getHeight();
  130.             /**
  131.              * 设置logo的大小,设置为二维码图片的25%,因为过大会盖掉二维码
  132.              */
  133.             int widthLogo = logo.getWidth(null)>codeWidth*2/13?(codeWidth*2/13):logo.getWidth(null),   
  134.                 heightLogo = logo.getHeight(null)>codeHeight*2/13?(codeHeight*2/13):logo.getWidth(null);  
  135.                
  136.             /**
  137.              * 计算图片放置位置  
  138.              * logo放在中心
  139.              */
  140.             int x = (codeWidth - widthLogo) / 2;
  141.             int y = (codeHeight - heightLogo) / 2;
  142.             int radius = 14;//圆角范围
  143.             
  144.             //填充与logo大小类似的扁平化圆角矩形背景
  145.             graphics2.setComposite(AlphaComposite.Src);
  146.             graphics2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  147.             graphics2.setColor(Color.WHITE);
  148.             graphics2.fill(new RoundRectangle2D.Float(x-2, y-2, widthLogo+4, heightLogo+4,radius,radius));
  149.             graphics2.setComposite(AlphaComposite.SrcAtop);
  150.             
  151.             //开始绘制logo图片  
  152.             graphics2.drawImage(logo, x, y, widthLogo, heightLogo, null);  
  153.                
  154.             if(!ImageIO.write(image, format, file)){  
  155.                 throw new IOException("Could not write an image of format " + format + " to " + file);   
  156.             }
  157.         } catch (Exception e) {
  158.             throw e;
  159.         }finally{
  160.             if(graphics2!=null){
  161.                 graphics2.dispose();  
  162.             }
  163.             if(logo!=null){
  164.                 logo.flush();  
  165.             }
  166.             if(image!=null){
  167.                 image.flush();
  168.             }
  169.         }
  170.     }
  171.       
  172.     public static BufferedImage toBufferedImage(BitMatrix matrix){  
  173.         int width = matrix.getWidth();  
  174.         int height = matrix.getHeight();  
  175.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  176.            
  177.         for(int x=0;x<width;x++){  
  178.             for(int y=0;y<height;y++){  
  179.                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
  180.             }  
  181.         }  
  182.         return image;     
  183.     }  
  184.      
  185.     public static void main(String[] args) {
  186.         String contents="http://www.baidu.com";
  187.         String imgPath = "D:/zxing/zxing.png";
  188.         String logoPath = "D:/logo.png";
  189.         QRCodeUtil.encode(contents, 200, 200, imgPath,logoPath);
  190.         QRCodeUtil.decode(imgPath);
  191.     }
  192. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP