java程序生成二维码

java设计生成二维码

在物联网的时代,二维码是个很重要的东西了,现在无论什么东西都要搞个二维码标志,唯恐落伍,就差人没有用二维码识别了。也许有一天生分证或者户口本都会用二维码识别了。今天心血来潮,看见别人都为自己的博客添加了二维码,我也想搞一个测试一下.

主要用来实现两点:

1. 生成任意文字的二维码.

2. 在二维码的中间加入图像.

一、准备工作。

准备QR二维码3.0 版本的core包和一张jpg图片。


下载QR二维码包。

首先得下载 zxing.jar 包, 我这里用的是3.0 版本的core

下载地址: 现在已经迁移到了github: https://github.com/zxing/zxing/wiki/Getting-Started-Developing,

当然你也可以从maven仓库下载jar http://central.maven.org/maven2/com/google/zxing/core/




  二、程序设计

 1、启动eclipse,新建一个Java项目,命好项目名(本例取名为QRCodeSoft)。点下一步:

 
   2、导入zxing.jar , 我这里用的是3.0 版本的core包:点“添加外部JAR(X)…”。






   3、新建两个类,分别是:

BufferedImageLuminanceSource.java

QRCodeUtil.java


 

关键代码在于:BufferedImageLuminanceSource.java QRCodeUtil.java , 其中测试的main 方法位于QRCodeUtil.java 中。

BufferedImageLuminanceSource.java程序代码:

                                                                                                                                                                                                                   package qrcodesoft;

[java]  view plain  copy
 print ?
  1. <span style="background-color: rgb(255, 255, 255);">  
  2. import java.awt.Graphics2D;  
  3. import java.awt.geom.AffineTransform;  
  4. import java.awt.image.BufferedImage;  
  5.   
  6. import com.google.zxing.LuminanceSource;  
  7.   
  8. public class BufferedImageLuminanceSource extends LuminanceSource {  
  9.     private final BufferedImage image;  
  10.     private final int left;  
  11.     private final int top;  
  12.   
  13.     public BufferedImageLuminanceSource(BufferedImage image) {  
  14.         this(image, 00, image.getWidth(), image.getHeight());  
  15.     }  
  16.   
  17.     public BufferedImageLuminanceSource(BufferedImage image, int left,  
  18.             int top, int width, int height) {  
  19.         super(width, height);  
  20.   
  21.         int sourceWidth = image.getWidth();  
  22.         int sourceHeight = image.getHeight();  
  23.         if (left + width > sourceWidth || top + height > sourceHeight) {  
  24.             throw new IllegalArgumentException(  
  25.                     "Crop rectangle does not fit within image data.");  
  26.         }  
  27.   
  28.         for (int y = top; y < top + height; y++) {  
  29.             for (int x = left; x < left + width; x++) {  
  30.                 if ((image.getRGB(x, y) & 0xFF000000) == 0) {  
  31.                     image.setRGB(x, y, 0xFFFFFFFF); // = white  
  32.                 }  
  33.             }  
  34.         }  
  35.   
  36.         this.image = new BufferedImage(sourceWidth, sourceHeight,  
  37.                 BufferedImage.TYPE_BYTE_GRAY);  
  38.         this.image.getGraphics().drawImage(image, 00null);  
  39.         this.left = left;  
  40.         this.top = top;  
  41.     }  
  42.   
  43.      
  44.     public byte[] getRow(int y, byte[] row) {  
  45.         if (y < 0 || y >= getHeight()) {  
  46.             throw new IllegalArgumentException(  
  47.                     "Requested row is outside the image: " + y);  
  48.         }  
  49.         int width = getWidth();  
  50.         if (row == null || row.length < width) {  
  51.             row = new byte[width];  
  52.         }  
  53.         image.getRaster().getDataElements(left, top + y, width, 1, row);  
  54.         return row;  
  55.     }  
  56.   
  57.      
  58.     public byte[] getMatrix() {  
  59.         int width = getWidth();  
  60.         int height = getHeight();  
  61.         int area = width * height;  
  62.         byte[] matrix = new byte[area];  
  63.         image.getRaster().getDataElements(left, top, width, height, matrix);  
  64.         return matrix;  
  65.     }  
  66.   
  67.      
  68.     public boolean isCropSupported() {  
  69.         return true;  
  70.     }  
  71.   
  72.      
  73.     public LuminanceSource crop(int left, int top, int width, int height) {  
  74.         return new BufferedImageLuminanceSource(image, this.left + left,  
  75.                 this.top + top, width, height);  
  76.     }  
  77.   
  78.      
  79.     public boolean isRotateSupported() {  
  80.         return true;  
  81.     }  
  82.   
  83.      
  84.     public LuminanceSource rotateCounterClockwise() {  
  85.         int sourceWidth = image.getWidth();  
  86.         int sourceHeight = image.getHeight();  
  87.         AffineTransform transform = new AffineTransform(0.0, -1.01.0,  
  88.                 0.00.0, sourceWidth);  
  89.         BufferedImage rotatedImage = new BufferedImage(sourceHeight,  
  90.                 sourceWidth, BufferedImage.TYPE_BYTE_GRAY);  
  91.         Graphics2D g = rotatedImage.createGraphics();  
  92.         g.drawImage(image, transform, null);  
  93.         g.dispose();  
  94.         int width = getWidth();  
  95.         return new BufferedImageLuminanceSource(rotatedImage, top,  
  96.                 sourceWidth - (left + width), getHeight(), width);  
  97.     }  
  98. }</span>  

QRCodeUtil.java的程序代码:

                                                                                                                                                                                                                         

[java]  view plain  copy
 print ?
  1. <span style="background-color: rgb(255, 255, 255);">package qrcodesoft;  
  2.   
  3.   
  4. import java.awt.BasicStroke;  
  5. import java.awt.Graphics;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.Image;  
  8. import java.awt.Shape;  
  9. import java.awt.geom.RoundRectangle2D;  
  10. import java.awt.image.BufferedImage;  
  11. import java.io.File;  
  12. import java.io.OutputStream;  
  13. import java.util.Hashtable;  
  14. import java.util.Random;  
  15.   
  16. import javax.imageio.ImageIO;  
  17.   
  18. import com.google.zxing.BarcodeFormat;  
  19. import com.google.zxing.BinaryBitmap;  
  20. import com.google.zxing.DecodeHintType;  
  21. import com.google.zxing.EncodeHintType;  
  22. import com.google.zxing.MultiFormatReader;  
  23. import com.google.zxing.MultiFormatWriter;  
  24. import com.google.zxing.Result;  
  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. public class QRCodeUtil {  
  31.   
  32.     private static final String CHARSET = "utf-8";  
  33.     private static final String FORMAT_NAME = "JPG";  
  34.     // 二维码尺寸  
  35.     private static final int QRCODE_SIZE = 300;  
  36.     // LOGO宽度  
  37.     private static final int WIDTH = 60;  
  38.     // LOGO高度  
  39.     private static final int HEIGHT = 60;  
  40.   
  41.     private static BufferedImage createImage(String content, String imgPath,  
  42.             boolean needCompress) throws Exception {  
  43.         Hashtable hints = new Hashtable();  
  44.         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  
  45.         hints.put(EncodeHintType.CHARACTER_SET, CHARSET);  
  46.         hints.put(EncodeHintType.MARGIN, 1);  
  47.         BitMatrix bitMatrix = new MultiFormatWriter().encode(content,  
  48.                 BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);  
  49.         int width = bitMatrix.getWidth();  
  50.         int height = bitMatrix.getHeight();  
  51.         BufferedImage image = new BufferedImage(width, height,  
  52.                 BufferedImage.TYPE_INT_RGB);  
  53.         for (int x = 0; x < width; x++) {  
  54.             for (int y = 0; y < height; y++) {  
  55.                 image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000  
  56.                         : 0xFFFFFFFF);  
  57.             }  
  58.         }  
  59.         if (imgPath == null || "".equals(imgPath)) {  
  60.             return image;  
  61.         }  
  62.         // 插入图片  
  63.         QRCodeUtil.insertImage(image, imgPath, needCompress);  
  64.         return image;  
  65.     }  
  66.   
  67.      
  68.     private static void insertImage(BufferedImage source, String imgPath,  
  69.             boolean needCompress) throws Exception {  
  70.         File file = new File(imgPath);  
  71.         if (!file.exists()) {  
  72.             System.err.println(""+imgPath+"   该文件不存在!");  
  73.             return;  
  74.         }  
  75.         Image src = ImageIO.read(new File(imgPath));  
  76.         int width = src.getWidth(null);  
  77.         int height = src.getHeight(null);  
  78.         if (needCompress) { // 压缩LOGO  
  79.             if (width > WIDTH) {  
  80.                 width = WIDTH;  
  81.             }  
  82.             if (height > HEIGHT) {  
  83.                 height = HEIGHT;  
  84.             }  
  85.             Image image = src.getScaledInstance(width, height,  
  86.                     Image.SCALE_SMOOTH);  
  87.             BufferedImage tag = new BufferedImage(width, height,  
  88.                     BufferedImage.TYPE_INT_RGB);  
  89.             Graphics g = tag.getGraphics();  
  90.             g.drawImage(image, 00null); // 绘制缩小后的图  
  91.             g.dispose();  
  92.             src = image;  
  93.         }  
  94.         // 插入LOGO  
  95.         Graphics2D graph = source.createGraphics();  
  96.         int x = (QRCODE_SIZE - width) / 2;  
  97.         int y = (QRCODE_SIZE - height) / 2;  
  98.         graph.drawImage(src, x, y, width, height, null);  
  99.         Shape shape = new RoundRectangle2D.Float(x, y, width, width, 66);  
  100.         graph.setStroke(new BasicStroke(3f));  
  101.         graph.draw(shape);  
  102.         graph.dispose();  
  103.     }  
  104.   
  105.      
  106.     public static void encode(String content, String imgPath, String destPath,  
  107.             boolean needCompress) throws Exception {  
  108.         BufferedImage image = QRCodeUtil.createImage(content, imgPath,  
  109.                 needCompress);  
  110.         mkdirs(destPath);  
  111.         String file = new Random().nextInt(99999999)+".jpg";  
  112.         ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));  
  113.     }  
  114.   
  115.      
  116.     public static void mkdirs(String destPath) {  
  117.         File file =new File(destPath);     
  118.         //当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)  
  119.         if (!file.exists() && !file.isDirectory()) {  
  120.             file.mkdirs();  
  121.         }  
  122.     }  
  123.   
  124.      
  125.     public static void encode(String content, String imgPath, String destPath)  
  126.             throws Exception {  
  127.         QRCodeUtil.encode(content, imgPath, destPath, false);  
  128.     }  
  129.   
  130.      
  131.     public static void encode(String content, String destPath,  
  132.             boolean needCompress) throws Exception {  
  133.         QRCodeUtil.encode(content, null, destPath, needCompress);  
  134.     }  
  135.   
  136.      
  137.     public static void encode(String content, String destPath) throws Exception {  
  138.         QRCodeUtil.encode(content, null, destPath, false);  
  139.     }  
  140.   
  141.      
  142.     public static void encode(String content, String imgPath,  
  143.             OutputStream output, boolean needCompress) throws Exception {  
  144.         BufferedImage image = QRCodeUtil.createImage(content, imgPath,  
  145.                 needCompress);  
  146.         ImageIO.write(image, FORMAT_NAME, output);  
  147.     }  
  148.   
  149.      
  150.     public static void encode(String content, OutputStream output)  
  151.             throws Exception {  
  152.         QRCodeUtil.encode(content, null, output, false);  
  153.     }  
  154.   
  155.      
  156.     public static String decode(File file) throws Exception {  
  157.         BufferedImage image;  
  158.         image = ImageIO.read(file);  
  159.         if (image == null) {  
  160.             return null;  
  161.         }  
  162.         BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(  
  163.                 image);  
  164.         BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
  165.         Result result;  
  166.         Hashtable hints = new Hashtable();  
  167.         hints.put(DecodeHintType.CHARACTER_SET, CHARSET);  
  168.         result = new MultiFormatReader().decode(bitmap, hints);  
  169.         String resultStr = result.getText();  
  170.         return resultStr;  
  171.     }  
  172.   
  173.      
  174.     public static String decode(String path) throws Exception {  
  175.         return QRCodeUtil.decode(new File(path));  
  176.     }  
  177.      
  178.      
  179.     public static void main(String[] args) throws Exception {  
  180.         String text = "http://www.dans88.com.cn";  
  181.         QRCodeUtil.encode(text, "d:/MyWorkDoc/my180.jpg""d:/MyWorkDoc"true);  
  182.     }  
  183.      
  184. }  
  185. </span>  


生成不带logo 的二维码

程序代码

 

[java]  view plain  copy
 print ?
  1. <span style="background-color: rgb(255, 255, 255);">public static void main(String[] args) throws Exception {  
  2.         String text = "http://www.dans88.com.cn";  
  3.         QRCodeUtil.encode(text,"","d:/MyWorkDoc",true);</span>  

 

运行这个测试方法,生成的二维码不带 logo , 样式如下:







有兴趣可以用手机扫描一下

生成带logo 的二维码 
logo
 可以用自己的头像,或者自己喜欢的一个图片都可以 , 采用如下代码

程序代码

 

[java]  view plain  copy
 print ?
  1. <span style="background-color: rgb(255, 255, 255);">public static void main(String[] args) throws Exception {  
  2.         String text = "http://www.dans88.com.cn";  
  3.         QRCodeUtil.encode(text, "d:/MyWorkDoc/my180.jpg""d:/MyWorkDoc"true);  
  4.     }</span>  

唯一的区别是,在前面的基础上指定了logo 的地址,这里测试都用了c盘的图片文件





用手机扫描,能出现要出现的文字,点击就进入自己的网站,看起来还不错, 整个源代码,提供在下载测试:

Java barcode sample

本文转载于:http://blog.sina.com.cn/s/blog_5a6efa330102v1lb.html

 

猜你喜欢

转载自blog.csdn.net/marvel_cheng/article/details/53504700
今日推荐