最近在做一个小项目,需要手机扫描二维码进行下载或者信息采集,在服务器端需要生成个二维码需要生成个相关的二维码供手机端使用,本以为这会是个棘手的问题,没想到在网上有现成的,这省去了我不少麻烦,虽然网上已经有很多资料,在这还是整理了下来,去了给别人作参考外,等下次再用到的时候,就可以手到擒来了。好了,我闲话少说,切入正题。
首先需要引入jar包,在这里我提供了下载地址:http://download.youkuaiyun.com/detail/yuzhuangzhuang/5983615
引入jar包后还需要一个官方的工具类,在这里我将源码贴出,直接复制就可以了。
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
/**
* 二位码生成工具类
* @author Google
*
*/
public final class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private MatrixToImageWriter() {}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
public static void main(String args[]) {
try {
//二维码中的内容,根据需求自己更改
String content = "10086;www.baidu.com";
//二维码存放地址
String path = "D:/";
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400);
File file1 = new File(path,"二维码图片.jpg");
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
1852

被折叠的 条评论
为什么被折叠?



