二维码显示在网页上

servlet

String code =""; 
        code = req.getParameter("code");
        if (code == null && !"".equals(code)) {
            code = "duwenlei";
        }
        try {
            TestImg.generateImg(code);
            resp.setHeader("Content-Type", "image/png");
            InputStream in = new FileInputStream(new File("f://test.png"));
            ServletOutputStream out = resp.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

utils

public class TestImg {
    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;
    public static void generateImg(String code) throws Exception{
        File file = new File("f://test.png");
        TestImg test = new TestImg();
        test.encode(code, file,BarcodeFormat.QR_CODE, 200, 200, null);
        test.decode(file);
    }

    public void encode(String contents, File file, BarcodeFormat format,
            int width, int height, Map<EncodeHintType, ?> hints) throws Exception {
        BitMatrix bitMatrix =  new MultiFormatWriter().encode(contents, format, width, height);
        writeToFile(bitMatrix, "png", file);
    }
    /**
     * 生成二维码图片<br>
     * 
     * @param matrix
     * @param format
     *            图片格式
     * @param file
     *            生成二维码图片位置
     * @throws IOException
     */
    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        ImageIO.write(image, format, file);
    }

    /**
     * 生成二维码内容<br>
     * 
     * @param matrix
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 解析QRCode二维码
     */
    @SuppressWarnings("unchecked")
    public void decode(File file) {
        try {
            BufferedImage image;
            try {
                image = ImageIO.read(file);
                if (image == null) {
                    System.out.println("Could not decode image");
                }
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result result;
                @SuppressWarnings("rawtypes")
                Hashtable hints = new Hashtable();
                //解码设置编码方式为:utf-8
                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
                result = new MultiFormatReader().decode(bitmap, hints);
                String resultStr = result.getText();
                System.out.println("解析后内容:" + resultStr);
            } catch (IOException ioe) {
                System.out.println(ioe.toString());
            } catch (ReaderException re) {
                System.out.println(re.toString());
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
}

jsp

<body>
    <h1>TestWeb</h1>
    <input type="text" name="code" id="codeValue"/><br/><img src="/TestWeb/TestImgServlet" width="200" height="200" onclick="change(this)"/>
</body>
<script type="text/javascript">
    function change(obj){
        var code =  document.getElementById("codeValue").value;
        var codes = obj.src ;
        if(codes.indexOf("?") != -1){
            var url = codes.substring(0,codes.indexOf("?"));
            obj.src = url+"?code="+code;
            return;
        }
        obj.src = obj.src+"?code="+code;
    }
</script>
如果有使用请标明来源:http://www.cnblogs.com/duwenlei/
原文地址:https://www.cnblogs.com/duwenlei/p/3696738.html