{"success":true,"code":0,"msg":"","data":{"themeEx":{"tid":106,"replies":0,"views":3492,"searchs":0,"topGmtUpdate":null,"top":false},"theme":{"id":106,"title":"java 生成二维码","content":"工具类\n
\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport javax.imageio.ImageIO;\nimport com.google.zxing.common.BitMatrix;\npublic class QRUtil {\n\tprivate static final int BLACK = 0xFF000000;\n\tprivate static final int WHITE = 0xFFFFFFFF;\n\tpublic static BufferedImage toBufferedImage(BitMatrix matrix) {\n\t\tint width = matrix.getWidth();\n\t\tint height = matrix.getHeight();\n\t\tBufferedImage image = new BufferedImage(width, height,\n\t\t\t\tBufferedImage.TYPE_INT_RGB);\n\t\tfor (int x = 0; x < width; x++) {\n\t\t\tfor (int y = 0; y < height; y++) {\n\t\t\t\timage.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);\n\t\t\t}\n\t\t}\n\t\treturn image;\n\t}\n\t/**\n\t * 转换成图片文件\n\t * @param matrix\n\t * @param format\n\t * @param file\n\t * @throws IOException\n\t */\n\tpublic static void writeToFile(BitMatrix matrix, String format, File file)\n\t\t\tthrows IOException {\n\t\tBufferedImage image = toBufferedImage(matrix);\n\t\tif (!ImageIO.write(image, format, file)) {\n\t\t\tthrow new IOException(\"Could not write an image of format \"\n\t\t\t\t\t+ format + \" to \" + file);\n\t\t}\n\t}\n\t/**\n\t * 转换成文件流\n\t * @param matrix\n\t * @param format\n\t * @param stream\n\t * @throws IOException\n\t */\n\tpublic static void writeToStream(BitMatrix matrix, String format,\n\t\t\tOutputStream stream) throws IOException {\n\t\tBufferedImage image = toBufferedImage(matrix);\n\t\tif (!ImageIO.write(image, format, stream)) {\n\t\t\tthrow new IOException(\"Could not write an image of format \"\n\t\t\t\t\t+ format);\n\t\t}\n\t}\n}\n\n
\n\t二维码的依赖包\n
\n\n\t
\n
com.google.zxingcore3.2.0\n
\n\tController:\n
\n\n\t
\n
@RequestMapping(\"/getQR\")\npublic void getQR(String url,HttpServletResponse response){\n\tint width = 250;\n\tint height = 250;\n\t// 二维码的图片格式\n\tString format = \"gif\";\n\tHashtable\nhints = new Hashtable ();\n\t// 内容所使用编码\n\thints.put(EncodeHintType.CHARACTER_SET, \"utf-8\");\n\tBitMatrix bitMatrix;\n\ttry {\n\t\tbitMatrix = new MultiFormatWriter().encode(url,\n\t\t\t\tBarcodeFormat.QR_CODE, width, height, hints);\n\t\tQRUtil.writeToStream(bitMatrix, format, response.getOutputStream());\n\t} catch (WriterException | IOException e) {\n\t\t// TODO Auto-generated catch block\n\t\te.printStackTrace();\n\t}\n}
\n\t
\n