使用zxing生成二维码

来源:互联网 发布:观为监测大数据 编辑:程序博客网 时间:2024/05/16 06:15

使用zxing批量在做好的立牌背景图的指定位置上,把指定的文本内容(链接地址、文本等)生成二维码并放在该位置,

最后加上立牌编号。

步骤:

1).做好背景图,如下图:

扫一扫添加关注


2).生成二维码BufferedImage对象。代码如下:

[java] view plain copy
  1. /** 
  2.      *  
  3.      * @Title: toBufferedImage 
  4.      * @Description: 把文本转化成二维码图片对象 
  5.      * @param text 
  6.      *            二维码内容 
  7.      * @param width 
  8.      *            二维码高度 
  9.      * @param height 
  10.      *            二位宽度 
  11.      * @param 
  12.      * @param Exception 
  13.      *            设定文件 
  14.      * @return BufferedImage 返回类型 
  15.      * @throws 
  16.      */  
  17.     public static BufferedImage toBufferedImage(String text, int width,  
  18.             int height) throws Exception {  
  19.         int BLACK = 0xFF000000;  
  20.         int WHITE = 0xFFFFFFFF;  
  21.         Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();  
  22.         hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码  
  23.         hints.put(EncodeHintType.MARGIN, 1);  
  24.         BitMatrix matrix = new MultiFormatWriter().encode(text,  
  25.                 BarcodeFormat.QR_CODE, width, height, hints);  
  26.         BufferedImage image = new BufferedImage(width, height,  
  27.                 BufferedImage.TYPE_INT_RGB);  
  28.         for (int x = 0; x < width; x++) {  
  29.             for (int y = 0; y < height; y++) {  
  30.                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
  31.             }  
  32.         }  
  33.         return image;  
  34.     }  


3).在立牌背景图的指定位置上生成二维码,代码如下:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      *  
  3.      * @Title: markImageByCode 
  4.      * @Description: 向图片指定位置增加二维码 
  5.      * @param img 
  6.      *            二维码image对象 
  7.      * @param srcImgPath 
  8.      *            背景图 
  9.      * @param targerPath 
  10.      *            目标图 
  11.      * @param positionWidth 
  12.      *            位置横坐标 
  13.      * @param positionHeight 
  14.      *            位置纵坐标 
  15.      * @return void 返回类型 
  16.      * @throws 
  17.      */  
  18.     public static void markImageByCode(Image img, String srcImgPath,  
  19.             String targerPath, int positionWidth, int positionHeight) {  
  20.         OutputStream os = null;  
  21.         try {  
  22.   
  23.             Image srcImg = ImageIO.read(new File(srcImgPath));  
  24.   
  25.             BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),  
  26.                     srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);  
  27.   
  28.             // 1、得到画笔对象  
  29.             Graphics2D g = buffImg.createGraphics();  
  30.   
  31.             // 2、设置对线段的锯齿状边缘处理  
  32.             g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
  33.                     RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
  34.   
  35.             g.drawImage(  
  36.                     srcImg.getScaledInstance(srcImg.getWidth(null),  
  37.                             srcImg.getHeight(null), Image.SCALE_SMOOTH), 00,  
  38.                     null);  
  39.   
  40.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,  
  41.                     alpha));  
  42.   
  43.             // 3、二维码位置  
  44.             g.drawImage(img, positionWidth, positionHeight, null);  
  45.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));  
  46.             // 4、释放资源  
  47.             g.dispose();  
  48.   
  49.             // 5、生成图片(建议生成PNG的,jpg会失真)  
  50.             os = new FileOutputStream(targerPath);  
  51.             ImageIO.write(buffImg, "PNG", os);  
  52.   
  53.             System.out.println("二维码图片生成成功");  
  54.   
  55.         } catch (Exception e) {  
  56.             e.printStackTrace();  
  57.         } finally {  
  58.             try {  
  59.                 if (null != os)  
  60.                     os.close();  
  61.             } catch (Exception e) {  
  62.                 e.printStackTrace();  
  63.             }  
  64.         }  
  65.     }  


4).在立牌上加上立牌编号

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      *  
  3.      * @Title: pressText 
  4.      * @Description:向图片指定位置加上文字 
  5.      * @param pressText 
  6.      *            文字内容 
  7.      * @param srcImageFile 
  8.      *            原图片 
  9.      * @param destImageFile 
  10.      *            目标图片 
  11.      * @param x 
  12.      *            横坐标 
  13.      * @param y 
  14.      *            纵坐标 
  15.      * @param alpha 
  16.      *            透明度 
  17.      * @return void 返回类型 
  18.      * @throws 
  19.      */  
  20.     public final static void pressText(String pressText, String srcImageFile,  
  21.             String destImageFile, int x, int y, float alpha) {  
  22.         try {  
  23.             File img = new File(srcImageFile);  
  24.             Image src = ImageIO.read(img);  
  25.             int width = src.getWidth(null);  
  26.             int height = src.getHeight(null);  
  27.             BufferedImage image = new BufferedImage(width, height,  
  28.                     BufferedImage.TYPE_INT_RGB);  
  29.             Graphics2D g = image.createGraphics();  
  30.             // 开文字抗锯齿 去文字毛刺  
  31.             g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,  
  32.                     RenderingHints.VALUE_TEXT_ANTIALIAS_ON);  
  33.             g.drawImage(src, 00, width, height, null);  
  34.             // 设置颜色  
  35.             g.setColor(new Color(898787));  
  36.             // 设置 Font  
  37.             g.setFont(new Font("方正兰亭中黑_GBK", Font.BOLD, 14));  
  38.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,  
  39.                     alpha));  
  40.             // 第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y) .  
  41.             g.drawString(pressText, x, y);  
  42.             g.dispose();  
  43.             ImageIO.write((BufferedImage) image, "PNG"new File(destImageFile));// 输出到文件流  
  44.         } catch (Exception e) {  
  45.             e.printStackTrace();  
  46.         }  
  47.     }  

示例:

代码:

测试代码

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. public class codeTest {  
  2.     public static void main(String[] args) throws Exception {  
  3.         String text = "http://www.xxx.com/"; // 二维码内容  
  4.   
  5.         // 生成二维码  
  6.         //生成图片二维码存放目录  
  7.         String targetPath = "f:/qrcode/targetimg/" + Utils.toStr();  
  8.         //创建目录  
  9.         Utils.makeDirs(targetPath);  
  10.           
  11.         int begin = 100;//code 开始数字  
  12.         int end = 101;//code结束数字  
  13.         for (int i = begin; i <= end; i++) {  
  14.             //生成含日期的16位数字如20161214000001  
  15.             String code = Utils.toStr() + Utils.formateNumber(i);  
  16.             //获取二维码对象  
  17.             BufferedImage image = Utils.toBufferedImage(text  
  18.                     + "?payCode=" + code,240,240);  
  19.             //生成含背景图+二维码的立牌的图  
  20.             Utils.markImageByCode(image, "f:/qrcode/srcimg/src.png",  
  21.                     targetPath + "/" + code + ".png"340160);  
  22.             //立牌的图加上code编号  
  23.             Utils.pressText(code, targetPath + "/" + code + ".png", targetPath  
  24.                     + "/" + code + ".png"3904170.5f);  
  25.         }  
  26.         // 生成二维码  
  27.     }  
  28. }  

效果:

批量生成的图片效果图如下

批量图:

utils代码:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. package cn.utils.code;  
  2.   
  3. import java.awt.AlphaComposite;  
  4. import java.awt.Color;  
  5. import java.awt.Font;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.Image;  
  8. import java.awt.RenderingHints;  
  9. import java.awt.image.BufferedImage;  
  10. import java.io.File;  
  11. import java.io.FileOutputStream;  
  12. import java.io.OutputStream;  
  13. import java.text.DecimalFormat;  
  14. import java.text.SimpleDateFormat;  
  15. import java.util.Date;  
  16. import java.util.Hashtable;  
  17.   
  18. import javax.imageio.ImageIO;  
  19.   
  20. import com.google.zxing.BarcodeFormat;  
  21. import com.google.zxing.EncodeHintType;  
  22. import com.google.zxing.MultiFormatWriter;  
  23. import com.google.zxing.common.BitMatrix;  
  24.   
  25. /** 工具类. */  
  26. public abstract class Utils {  
  27.   
  28.     /** 日期格式:yyyy-MM-dd HH:mm:ss */  
  29.     public static String DF_DATETIME = "yyyyMMdd";  
  30.     private static float alpha = 1f;  
  31.   
  32.     /** 
  33.      *  
  34.      * @Title: toBufferedImage 
  35.      * @Description: 把文本转化成二维码图片对象 
  36.      * @param text 
  37.      *            二维码内容 
  38.      * @param width 
  39.      *            二维码高度 
  40.      * @param height 
  41.      *            二位宽度 
  42.      * @param 
  43.      * @param Exception 
  44.      *            设定文件 
  45.      * @return BufferedImage 返回类型 
  46.      * @throws 
  47.      */  
  48.     public static BufferedImage toBufferedImage(String text, int width,  
  49.             int height) throws Exception {  
  50.         int BLACK = 0xFF000000;  
  51.         int WHITE = 0xFFFFFFFF;  
  52.         Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();  
  53.         hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码  
  54.         hints.put(EncodeHintType.MARGIN, 1);  
  55.         BitMatrix matrix = new MultiFormatWriter().encode(text,  
  56.                 BarcodeFormat.QR_CODE, width, height, hints);  
  57.         BufferedImage image = new BufferedImage(width, height,  
  58.                 BufferedImage.TYPE_INT_RGB);  
  59.         for (int x = 0; x < width; x++) {  
  60.             for (int y = 0; y < height; y++) {  
  61.                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
  62.             }  
  63.         }  
  64.         return image;  
  65.     }  
  66.   
  67.     /** 
  68.      *  
  69.      * @Title: markImageByCode 
  70.      * @Description: 向图片指定位置增加二维码 
  71.      * @param img 
  72.      *            二维码image对象 
  73.      * @param srcImgPath 
  74.      *            背景图 
  75.      * @param targerPath 
  76.      *            目标图 
  77.      * @param positionWidth 
  78.      *            位置横坐标 
  79.      * @param positionHeight 
  80.      *            位置纵坐标 
  81.      * @return void 返回类型 
  82.      * @throws 
  83.      */  
  84.     public static void markImageByCode(Image img, String srcImgPath,  
  85.             String targerPath, int positionWidth, int positionHeight) {  
  86.         OutputStream os = null;  
  87.         try {  
  88.   
  89.             Image srcImg = ImageIO.read(new File(srcImgPath));  
  90.   
  91.             BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),  
  92.                     srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);  
  93.   
  94.             // 1、得到画笔对象  
  95.             Graphics2D g = buffImg.createGraphics();  
  96.   
  97.             // 2、设置对线段的锯齿状边缘处理  
  98.             g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
  99.                     RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
  100.   
  101.             g.drawImage(  
  102.                     srcImg.getScaledInstance(srcImg.getWidth(null),  
  103.                             srcImg.getHeight(null), Image.SCALE_SMOOTH), 00,  
  104.                     null);  
  105.   
  106.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,  
  107.                     alpha));  
  108.   
  109.             // 3、二维码位置  
  110.             g.drawImage(img, positionWidth, positionHeight, null);  
  111.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));  
  112.             // 4、释放资源  
  113.             g.dispose();  
  114.   
  115.             // 5、生成图片(建议生成PNG的,jpg会失真)  
  116.             os = new FileOutputStream(targerPath);  
  117.             ImageIO.write(buffImg, "PNG", os);  
  118.   
  119.             System.out.println("二维码图片生成成功");  
  120.   
  121.         } catch (Exception e) {  
  122.             e.printStackTrace();  
  123.         } finally {  
  124.             try {  
  125.                 if (null != os)  
  126.                     os.close();  
  127.             } catch (Exception e) {  
  128.                 e.printStackTrace();  
  129.             }  
  130.         }  
  131.     }  
  132.   
  133.     /** 
  134.      *  
  135.      * @Title: pressText 
  136.      * @Description:向图片指定位置加上文字 
  137.      * @param pressText 
  138.      *            文字内容 
  139.      * @param srcImageFile 
  140.      *            原图片 
  141.      * @param destImageFile 
  142.      *            目标图片 
  143.      * @param x 
  144.      *            横坐标 
  145.      * @param y 
  146.      *            纵坐标 
  147.      * @param alpha 
  148.      *            透明度 
  149.      * @return void 返回类型 
  150.      * @throws 
  151.      */  
  152.     public final static void pressText(String pressText, String srcImageFile,  
  153.             String destImageFile, int x, int y, float alpha) {  
  154.         try {  
  155.             File img = new File(srcImageFile);  
  156.             Image src = ImageIO.read(img);  
  157.             int width = src.getWidth(null);  
  158.             int height = src.getHeight(null);  
  159.             BufferedImage image = new BufferedImage(width, height,  
  160.                     BufferedImage.TYPE_INT_RGB);  
  161.             Graphics2D g = image.createGraphics();  
  162.             // 开文字抗锯齿 去文字毛刺  
  163.             g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,  
  164.                     RenderingHints.VALUE_TEXT_ANTIALIAS_ON);  
  165.             g.drawImage(src, 00, width, height, null);  
  166.             // 设置颜色  
  167.             g.setColor(new Color(898787));  
  168.             // 设置 Font  
  169.             g.setFont(new Font("方正兰亭中黑_GBK", Font.BOLD, 14));  
  170.             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,  
  171.                     alpha));  
  172.             // 第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y) .  
  173.             g.drawString(pressText, x, y);  
  174.             g.dispose();  
  175.             ImageIO.write((BufferedImage) image, "PNG"new File(destImageFile));// 输出到文件流  
  176.         } catch (Exception e) {  
  177.             e.printStackTrace();  
  178.         }  
  179.     }  
  180.   
  181.     // 日期转字符串  
  182.   
  183.     /** 将日期格式化为String,默认格式为yyyy-MM-dd HH:mm:ss,默认日期为当前日期. */  
  184.     public static String toStr() {  
  185.         return toStr(DF_DATETIME);  
  186.     }  
  187.   
  188.     /** 将日期格式化为String,格式由参数format指定,默认日期为当前日期,format值可使用本类常量或自定义. */  
  189.     public static String toStr(String format) {  
  190.         return toStr(format, new Date());  
  191.     }  
  192.   
  193.     /** 将日期格式化为String,默认格式为yyyy-MM-dd HH:mm:ss,日期由参数date指定. */  
  194.     public static String toStr(Date date) {  
  195.         return toStr(DF_DATETIME, date);  
  196.     }  
  197.   
  198.     /** 将日期格式化为String,格式由参数format指定,日期由参数date指定,format值可使用本类常量或自定义. */  
  199.     public static String toStr(String format, Date date) {  
  200.         return new SimpleDateFormat(format).format(date);  
  201.     }  
  202.   
  203.     public static String formateNumber(int num) {  
  204.         DecimalFormat df = new DecimalFormat("000000");  
  205.         String str2 = df.format(num);  
  206.         return str2;  
  207.     }  
  208.   
  209.     public static boolean makeDirs(String filePath) {  
  210.   
  211.         File folder = new File(filePath);  
  212.         return (folder.exists() && folder.isDirectory()) ? true : folder  
  213.                 .mkdirs();  
  214.     }  
  215.   
  216. }  

使用的技术:

1.使用的zxing生成二维码工具。

1)下载地址:

http://repo1.maven.org/maven2/com/google/zxing/javase/3.1.0/

2).maven配置

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <dependency>  
  2.             <groupId>com.google.zxing</groupId>  
  3.             <artifactId>core</artifactId>  
  4.             <version>2.2</version>  
  5.         </dependency> 
2 0