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
|
05
|
import
|
06
|
import
|
07
|
import
|
08
|
import
|
09
|
10
|
11
|
public class MatrixToImageWriter {
|
12
|
13
|
private final int BLACK = 0xFF000000 ;
|
14
|
private final int WHITE = 0xFFFFFFFF ;
|
15
|
16
|
private
|
17
|
18
|
19
|
public BufferedImage toBufferedImage(BitMatrix matrix) {
|
20
|
int
|
21
|
int
|
22
|
BufferedImage image = new BufferedImage(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
|
29
|
}
|
30
|
31
|
32
|
public void writeToFile(BitMatrix matrix, String format, File file)
|
33
|
throws
|
34
|
BufferedImage image = toBufferedImage(matrix);
|
35
|
if (!ImageIO.write(image, format, file)) {
|
36
|
throw IOException( "Could not write an image of format " + format + " to " + file);
|
37
|
}
|
38
|
}
|
39
|
40
|
41
|
public void writeToStream(BitMatrix matrix, String format, OutputStream stream)
|
42
|
throws
|
43
|
BufferedImage image = toBufferedImage(matrix);
|
44
|
if (!ImageIO.write(image, format, stream)) {
|
45
|
throw 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
|
13
|
14
|
/**
|
15
|
* @param args
|
16
|
* @throws Exception
|
17
|
*/
|
18
|
public void main(String[] args) throws Exception {
|
19
|
String text = "http://www.baidu.com" ;
|
20
|
int
300 ;
|
21
|
int
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就是二维码的内容里这里可以使普通的文字也可以是链接,很简单吧最后把生成的二维码图片给大家
时间: 2024-10-26 04:57:22