利用google的zxing生成二维码

本文介绍如何使用Java和ZXing库生成带有Logo的二维码图片,并提供了一个示例代码,演示了如何设置二维码参数、去除白边及整合Logo。

二维码,又叫二维条码。

1.Java这边的话生成二维码有很多开发的jar包如 zxing,qrcode ,下面是使用zxing的开发包来实现的。
ZXing项目是google code上面提供的一个关于条码编解码的开源项目。 
2.先下载zxing开发包,这里用到的只是core的jar包

我在项目中使用的core2.2.jar包。

下载地址:http://download.csdn.NET/download/tvcctv27tv/6841023

注:网上下载的core.jar使用JDK1.5;core2*.jar包使用JDK1.6;core3*.jar使用JDK1.7;

3. 源代码

[java]  view plain  copy
  1. package com.test.qrcodes;  
  2.   
  3. import java.awt.BasicStroke;  
  4. import java.awt.Color;  
  5. import java.awt.Graphics;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.Image;  
  8. import java.awt.image.BufferedImage;  
  9. import java.io.ByteArrayOutputStream;  
  10. import java.io.File;  
  11. import java.io.FileOutputStream;  
  12. import java.io.IOException;  
  13. import java.util.Hashtable;  
  14.   
  15. import javax.imageio.ImageIO;  
  16.   
  17. import junit.framework.Assert;  
  18.   
  19. import org.apache.commons.codec.binary.Base64;  
  20. import org.apache.commons.lang.StringUtils;  
  21.   
  22. import com.google.zxing.BarcodeFormat;  
  23. import com.google.zxing.EncodeHintType;  
  24. import com.google.zxing.MultiFormatWriter;  
  25. import com.google.zxing.common.BitMatrix;  
  26. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;  
  27.   
  28.   
  29. public class TestQRCodes {  
  30.   
  31.     private static final boolean NEEDCOMPRESS = false;  
  32.   
  33.     private static String LOGO_URL;  
  34.     // LOGO宽度  
  35.     private static final int WIDTH = 60;  
  36.     // LOGO高度  
  37.     private static final int HEIGHT = 60;  
  38.   
  39.     static{  
  40.         LOGO_URL = "";// 测试图片路径地址  
  41.     }  
  42.   
  43.     /** 
  44.      * 生成二维码的工具类 
  45.      *  
  46.      * @param data 
  47.      *            二维码中携带的数据 
  48.      * @param width 
  49.      *            二维码的宽度 
  50.      * @param height 
  51.      *            二维码的高度 
  52.      * @return 返回base64格式的图片(data:image/gif;base64,xxxx) <br> 
  53.      *         eg: <code> 
  54.      * <img alt="" src="data:image/gif;base64,xxxx"> 
  55.      * </code> 
  56.      */  
  57.     public static String createQRCode(String data, int width, int height, String isPicture) {  
  58.   
  59.         Assert.assertTrue("param data cannot empty.", data != null && data.trim().length() > 0);  
  60.   
  61.         Assert.assertTrue("param width and height must gt 0.", width > 0 && height > 0);  
  62.   
  63.         ByteArrayOutputStream bos = null;  
  64.   
  65.         MultiFormatWriter formatWriter = new MultiFormatWriter();  
  66.   
  67.         Hashtable<EncodeHintType, Object> param = new Hashtable<EncodeHintType, Object>();  
  68.         param.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);  
  69.         param.put(EncodeHintType.CHARACTER_SET, "utf-8");  
  70.         param.put(EncodeHintType.MARGIN, 0);  
  71.   
  72.         try{  
  73.             BitMatrix bitMatrix = formatWriter  
  74.                     .encode(data, BarcodeFormat.QR_CODE, width, height, param);  
  75.             // 1.1去白边  
  76.             int[] rec = bitMatrix.getEnclosingRectangle();  
  77.             int resWidth = rec[2] + 1;  
  78.             int resHeight = rec[3] + 1;  
  79.             BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
  80.             resMatrix.clear();  
  81.             for (int i = 0; i < resWidth; i++){  
  82.                 for (int j = 0; j < resHeight; j++){  
  83.                     if (bitMatrix.get(i + rec[0], j + rec[1])){  
  84.                         resMatrix.set(i, j);  
  85.                     }  
  86.                 }  
  87.             }  
  88.             int width1 = resMatrix.getWidth();  
  89.             int height1 = resMatrix.getHeight();  
  90.             BufferedImage qrcode = new BufferedImage(width1, height1, BufferedImage.TYPE_INT_RGB);  
  91.             for (int x = 0; x < width1; x++){  
  92.                 for (int y = 0; y < height1; y++){  
  93.                     qrcode.setRGB(x, y, resMatrix.get(x, y) == true ? Color.BLACK.getRGB() : Color.WHITE  
  94.                             .getRGB());  
  95.                 }  
  96.             }  
  97.             // 添加logo图片  
  98.             if (StringUtils.isNotEmpty(LOGO_URL) && StringUtils.isNotEmpty(isPicture)){  
  99.                 insertImage(width1, qrcode, LOGO_URL, NEEDCOMPRESS);  
  100.             }  
  101.             bos = new ByteArrayOutputStream();  
  102.             ImageIO.write(qrcode, "png", bos);  
  103.   
  104.             String img = StringUtils.deleteWhitespace(Base64.encodeBase64String(bos.toByteArray()));  
  105.             return String.format("data:image/png;base64,%s", img);  
  106.         } catch (Exception e){  
  107.             throw new RuntimeException(e);  
  108.         } finally{  
  109.             if (bos != null){  
  110.                 try{  
  111.                     bos.close();  
  112.                 } catch (IOException e){  
  113.                 }  
  114.             }  
  115.         }  
  116.   
  117.     }  
  118.   
  119.     private static void insertImage(int QRCODE_SIZE, BufferedImage source, String imgPath,  
  120.             boolean needCompress) throws Exception {  
  121.         File file = new File(imgPath);  
  122.         if (!file.exists()){  
  123.             System.err.println("" + imgPath + "   该文件不存在!");  
  124.             return;  
  125.         }  
  126.         Image src = ImageIO.read(new File(imgPath));  
  127.         int width = src.getWidth(null);  
  128.         int height = src.getHeight(null);  
  129.         if (needCompress){ // 压缩LOGO  
  130.             if (width > WIDTH){  
  131.                 width = WIDTH;  
  132.             }  
  133.             if (height > HEIGHT){  
  134.                 height = HEIGHT;  
  135.             }  
  136.             Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);  
  137.             BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  138.             Graphics g = tag.getGraphics();  
  139.             g.drawImage(image, 00null); // 绘制缩小后的图  
  140.             g.dispose();  
  141.             src = image;  
  142.         }  
  143.         // 插入LOGO  
  144.         Graphics2D graph = source.createGraphics();  
  145.         int x = (QRCODE_SIZE - width) / 2;  
  146.         int y = (QRCODE_SIZE - height) / 2;  
  147.         graph.drawImage(src, x, y, width, height, null);  
  148.         // Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);  
  149.         graph.setStroke(new BasicStroke(3f));  
  150.         // graph.draw(shape); 去除图片白边  
  151.         graph.dispose();  
  152.     }  
  153.   
  154.     /** 
  155.      * @param data 
  156.      *            二维码携带的数据 
  157.      * @param size 
  158.      *            二维码的宽、高 
  159.      * @return 
  160.      * @see WechatValidateUtils#generateQRCode(String, int, int) 
  161.      */  
  162.     public static String createQRCode(String data, int size, String isPicture) {  
  163.         return createQRCode(data, size, size, isPicture);  
  164.     }  
  165.   
  166.     // 测试  
  167.     public static void main(String[] args) throws Exception {  
  168.         // 生成二维码  
  169.         String url = "http://www.sina.com.cn";  
  170.         String src = createQRCode(url, 200"1");  
  171.         System.out.println(url.length());  
  172.         String html = "<img src=\"" + src + "\">";  
  173.         FileOutputStream ops = new FileOutputStream("D:\\QRCodeImage\\test.html");  
  174.         org.apache.commons.io.IOUtils.write(html, ops, "utf-8");  
  175.         ops.close();  
  176.     }  
  177. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值