需求:在pc或手机端,生成单独或域图片组合的二维码。不能依赖外界网络生成二维码途径。
解决:引入 com.google.zxing jar包
public static String getCode(String text) throws IOException, WriterException {
int width = 150; //二维码宽度
int height = 150; //二维码高度
int QRCOLOR = 0x201f1f; // 二维码颜色:黑色
int BGWHITE = 0xFFFFFF; //二维码背景颜色:白色
//设置默认编码格式和容错率
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN,0);
//开始生成二维码图片
BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
//设置二维码背景色
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.setRG