码迷,mamicode.com
首页 > 编程语言 > 详细

Java 生成二维码

时间:2015-05-10 23:46:07      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

1.java这边的话生成二维码有很多开发的jar包如zxing,qrcode.q前者是谷歌开发的后者则是小日本开发的,这里的话我使用zxing的开发包来弄


2.先下载zxing开发包,这里用到的只是core那个jar包


3.使用zxing开发还需要一个类,代码如下

01 package org.lxh;
02 import com.google.zxing.common.BitMatrix;
03  
04 import javax.imageio.ImageIO;
05 import java.io.File;
06 import java.io.OutputStream;
07 import java.io.IOException;
08 import java.awt.image.BufferedImage;
09  
10  
11 public final class MatrixToImageWriter {
12  
13 private static final int BLACK = 0xFF000000;
14 private static final int WHITE = 0xFFFFFFFF;
15  
16 private MatrixToImageWriter() {}
17  
18  
19 public static BufferedImage toBufferedImage(BitMatrix matrix) {
20 int width = matrix.getWidth();
21 int height = matrix.getHeight();
22 BufferedImage image = newBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
23 for (int x = 0; x < width; x++) {
24 for (int y = 0; y < height; y++) {
25 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
26 }
27 }
28 return image;
29 }
30  
31  
32 public static void writeToFile(BitMatrix matrix, String format, File file)
33 throws IOException {
34 BufferedImage image = toBufferedImage(matrix);
35 if (!ImageIO.write(image, format, file)) {
36 throw new IOException("Could not write an image of format "+ format + " to " + file);
37 }
38 }
39  
40  
41 public static voidwriteToStream(BitMatrix matrix, String format, OutputStream stream)
42 throws IOException {
43 BufferedImage image = toBufferedImage(matrix);
44 if (!ImageIO.write(image, format, stream)) {
45 throw new IOException("Could not write an image of format " + format);
46 }
47 }
48  
49 }

4.借助上面的类生成二维码

01 package org.lxh;
02  
03 import java.io.File;
04 import java.util.Hashtable;
05  
06 import com.google.zxing.BarcodeFormat;
07 import com.google.zxing.EncodeHintType;
08 import com.google.zxing.MultiFormatWriter;
09 import com.google.zxing.WriterException;
10 import com.google.zxing.common.BitMatrix;
11  
12 public class Test {
13  
14 /**
15 * @param args
16 * @throws Exception
17 */
18 public static void main(String[] args) throws Exception {
19 String text = "http://www.baidu.com";
20 int width = 300;
21 int height = 300;
22 //二维码的图片格式
23 String format = "gif";
24 Hashtable hints = new Hashtable();
25 //内容所使用编码
26 hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
27 BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
28 BarcodeFormat.QR_CODE, width, height, hints);
29 //生成二维码
30 File outputFile = new File("d:"+File.separator+"new.gif");
31 MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
32  
33 }
34  
35 }

text就是二维码的内容里这里可以使普通的文字也可以是链接,很简单吧最后把生成的二维码图片给大家

Java 生成二维码

标签:

原文地址:http://www.cnblogs.com/wicrecend/p/4493272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!