/**
* 生成一个二维码图片
*
* @param width
* @param height
* @param content
* @return
* @throws WriterException
* @throws IOException
*/
public static byte[] createQRCode(int width, int height, String content) throws WriterException, IOException {
// 二维码基本参数设置
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码字符集utf-8
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 设置纠错等级L/M/Q/H,纠错等级越高越不易识别,当前设置等级为最高等级H
hints.put(EncodeHintType.MARGIN, 0);// 可设置范围为0-10,但仅四个变化0 1(2) 3(4 5 6) 7(8 9 10)
// 生成图片类型为QRCode
BarcodeFormat format = BarcodeFormat.QR_CODE;
// 创建位矩阵对象
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, format, width, height, hints);
// 设置位矩阵转图片的参数
// MatrixToImageConfig config = new MatrixToImageConfig(Color.black.getRGB(), Color.white.getRGB());
// 位矩阵对象转流对象
ByteArrayOutputStream os = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", os);
return os.toByteArray();
}
public static void main(String[] args) throws WriterException, IOException {
byte[] b = createQRCode(100, 100, "http://www.ip111.cn/");
OutputStream os = new FileOutputStream("D:\\bestme.png");
os.write(b);
os.close();
}
//需要引入Qrcode的jar包使用,展示图片生成的二维码
// private static boolean encode(String srcValue, String qrcodePicfilePath) {
// int MAX_DATA_LENGTH = 200;
// byte[] d = srcValue.getBytes();
// int dataLength = d.length;
// int imageWidth = 113;
// int imageHeight = imageWidth;
// BufferedImage bi = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
// Graphics2D g = bi.createGraphics();
// g.setBackground(Color.WHITE);
// g.clearRect(0, 0, imageWidth, imageHeight);
// g.setColor(Color.BLACK);
// if (dataLength > 0 && dataLength <= MAX_DATA_LENGTH) {
// Qrcode qrcode = new Qrcode();
// qrcode.setQrcodeErrorCorrect('M');
// qrcode.setQrcodeEncodeMode('B');
// qrcode.setQrcodeVersion(5);
// boolean[][] b = qrcode.calQrcode(d);
// int qrcodeDataLen = b.length;
// for (int i = 0; i < qrcodeDataLen; i++) {
// for (int j = 0; j < qrcodeDataLen; j++) {
// if (b[j][i]) {
// g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
// }
// }
// }
// System.out.println("二维码成功生成!!");
//
// } else {
// System.out.println(dataLength + "大于" + MAX_DATA_LENGTH);
// return false;
// }
// g.dispose();
// bi.flush();
// File f = new File(qrcodePicfilePath);
// String suffix = f.getName().substring(f.getName().indexOf(".") + 1, f.getName().length());
// System.out.println("二维码输出成功!!");
// try {
// ImageIO.write(bi, suffix, f);
// } catch (IOException ioe) {
// System.out.println("二维码生成失败" + ioe.getMessage());
// return false;
// }
// return true;
//
// }
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。