java开发微信二维码
生活随笔
收集整理的這篇文章主要介紹了
java开发微信二维码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
要用到一個jar包QRcode.jar
主要用到了com.swetake.util.Qrcode這個類。API鏈接如下:
http://www.swetake.com/qrcode/java/docs/index.html
以本人博客首頁為例:
代碼如下:(生成一個固定內容的二維碼以圖片形式輸出到文件中)
CreateTwoBarImage.java(一個普通的java類)
運行結果:
掃碼之后顯示的就是一個字符串“lmb”,如果我們想通過掃碼訪問一個網址,該怎么改進呢?
代碼如下:(生成二維碼顯示到網頁上)
PrintTwoBarCodeServlet、qrcode.jsp
PrintTwoBarCodeServlet.java
package com.lmb;import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter;import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import com.swetake.util.Qrcode;public class PrintTwoBarCodeServlet extends HttpServlet {/*** 專門用來生成二維碼圖片的servlet*/private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {String code = request.getParameter("code");Qrcode testQrcode = new Qrcode();testQrcode.setQrcodeErrorCorrect('M');testQrcode.setQrcodeEncodeMode('B');testQrcode.setQrcodeVersion(7);byte[] d = code.getBytes("gbk");BufferedImage image = new BufferedImage(98, 98,BufferedImage.TYPE_BYTE_BINARY);Graphics2D g = image.createGraphics();g.setBackground(Color.WHITE);g.clearRect(0, 0, 98, 98);g.setColor(Color.BLACK);if (d.length > 0 && d.length < 120) {boolean[][] s = testQrcode.calQrcode(d);for (int i = 0; i < s.length; i++) {for (int j = 0; j < s.length; j++) {if (s[j][i]) {g.fillRect(j * 2 + 3, i * 2 + 3, 2, 2);}}}}g.dispose();image.flush();ImageIO.write(image, "jpg", response.getOutputStream());} }qrcode.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head> <title>顯示頁面</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css">.box{width:400px;height:300px;margin:0 auto;border:1px solid #39b2e2;text-align:center;color:red;}</style></head><body><div class="box"><h2>掃一掃開啟愛的密碼</h2><img src="printTwoBarCode.do?code=http://blog.csdn.net/lmb55"></div></body> </html>生成的二維碼:
掃一掃的顯示:
總結
以上是生活随笔為你收集整理的java开发微信二维码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Java线程】进程与线程
- 下一篇: 两类传输协议:TCPUDP总结