生成二维码所需jar包:http://www.swetake.com/qrcode/index-e.html
下载后生成jar包方法和上篇文章一样,通过Eclipse来生成导出
创建一个Java项目:
生成二维码:
package com.itstar.qrcode; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import com.swetake.util.Qrcode; /** *生成二维码 */ public class CreateQRCode { public static void main(String[] args) throws Exception { Qrcode x = new Qrcode(); x.setQrcodeErrorCorrect('M');// 纠错等级 L M H Q x.setQrcodeEncodeMode('B');// N代表数字,A代表a-z,B代表其他字符 x.setQrcodeVersion(7);// 版本 String qrData = "二维码"; int width = 67 + 12 * (7-1); int height = 67 + 12 * (7-1); // 依托了Java GUI画图工具 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 画图 Graphics2D gs = bufferedImage.createGraphics(); // 设置属性 gs.setBackground(Color.WHITE); gs.setColor(Color.BLACK); gs.clearRect(0, 0, width, height); int pixoff = 2;// 添加偏移量,不加有可能导致格式出错 // 填充内容 byte[] d = qrData.getBytes("gb2312");// 转为中文 if (d.length > 0 && d.length < 120) { boolean[][] s = x.calQrcode(d); for (int i = 0; i < s.length; i++) { for (int j = 0; j < s.length; j++) { if (s[j][i]) { gs.fillRect(j * 3+ pixoff, i * 3 + pixoff, 3, 3); } } } } //写入 结束 gs.dispose(); bufferedImage.flush(); ImageIO.write(bufferedImage, "png", new File("F:/code/qrcode.png")); } }
run as运行,在我们指定的文件下生成二维码:
这里的二维码width和height需要运用特定的公式来计算,如果是自己定义,二维码将会生成下面的二维码:
原因:定义的宽高太大,不符合版本,只能根据其定义的宽高公式来计算:
int width = 67 + 12 * (7-1); int height = 67 + 12 * (7-1);