/**
* 生成一个二维码图片 * * @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;//// }