
1.java这边的话生成二维码有很多开发的jar包如zxing,qrcode.q前者是谷歌开发的后者则是小日本开发的,这里的话我使用zxing的开发包来弄
2.先下载zxing开发包,这里用到的只是core那个jar包
3.使用zxing开发还需要一个类,代码如下
02 |
import com.google.zxing.common.BitMatrix;
|
04 |
import javax.imageio.ImageIO;
|
06 |
import java.io.OutputStream;
|
07 |
import java.io.IOException;
|
08 |
import java.awt.image.BufferedImage;
|
11 |
public final class MatrixToImageWriter {
|
13 |
private static final int BLACK = 0xFF000000 ;
|
14 |
private static final int WHITE = 0xFFFFFFFF ;
|
16 |
private MatrixToImageWriter() {}
|
19 |
public static BufferedImage toBufferedImage(BitMatrix matrix) {
|
20 |
int width = matrix.getWidth();
|
21 |
int height = matrix.getHeight();
|
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);
|
32 |
public static void writeToFile(BitMatrix matrix, String format, File file)
|
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);
|
41 |
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
|
43 |
BufferedImage image = toBufferedImage(matrix);
|
44 |
if (!ImageIO.write(image, format, stream)) {
|
45 |
throw new IOException( "Could not write an image of format " + format);
|
4.借助上面的类生成二维码
04 |
import java.util.Hashtable;
|
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;
|
18 |
public static void main(String[] args) throws Exception {
|
19 |
String text = "http://www.baidu.com" ;
|
23 |
String format = "gif" ;
|
24 |
Hashtable hints = new Hashtable();
|
26 |
hints.put(EncodeHintType.CHARACTER_SET, "utf-8" );
|
27 |
BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
|
28 |
BarcodeFormat.QR_CODE, width, height, hints);
|
30 |
File outputFile = new File( "d:" +File.separator+ "new.gif" );
|
31 |
MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
|
text就是二维码的内容里这里可以使普通的文字也可以是链接,很简单吧最后把生成的二维码图片给大家