带logo图片或不带logo图片的二维码生成与解析,亲测成功

最近公司需要实现二维码功能,本人经过一顿百度,终于实现了,因有3个功能:不带logo图片、带logo图片、解析二维码,篇幅较长,请耐心读之,直接复制粘贴即可。

前提:myeclipse10;jar包:core.jar,QRCode.jar;jquery.min.js,支持ajax即可

使用技术:jsp+servlet,ajax

项目下载地址:http://pan.baidu.com/s/1c0c2aPU

使用index.jsp测试二维码,直接上代码:

1、不带logo的二维码生成,有3个文件CreateAndShowEwm.java,TwoDimensionCode.java,TwoDimensionCodeImage.java:

1.1  CreateAndShowEwm.java 文件

package com.applet.another;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CreateAndShowEwm extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String _url=req.getParameter("_url");
String path="D:\\tomcat\\tomcat6.0.35\\webapps\\erweima\\pic.png";
TwoDimensionCode handler = new TwoDimensionCode();
handler.encoderQRCode(_url, path, "png");
PrintWriter writer=resp.getWriter();
writer.write(path.substring(path.lastIndexOf("\\")+1));
if(null!=writer){
writer.close();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
}

 

1.2 TwoDimensionCode.java 文件

 

package com.applet.another;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

import com.swetake.util.Qrcode;

public class TwoDimensionCode {

/**
* 生成二维码(QRCode)图片
* @param content 存储内容
* @param imgPath 图片路径
*/
public void encoderQRCode(String content, String imgPath) {
this.encoderQRCode(content, imgPath, "png", 7);
}

/**
* 生成二维码(QRCode)图片
* @param content 存储内容
* @param output 输出流
*/
public void encoderQRCode(String content, OutputStream output) {
this.encoderQRCode(content, output, "png", 7);
}

/**
* 生成二维码(QRCode)图片
* @param content 存储内容
* @param imgPath 图片路径
* @param imgType 图片类型
*/
public void encoderQRCode(String content, String imgPath, String imgType) {
this.encoderQRCode(content, imgPath, imgType, 7);
}

/**
* 生成二维码(QRCode)图片
* @param content 存储内容
* @param output 输出流
* @param imgType 图片类型
*/
public void encoderQRCode(String content, OutputStream output, String imgType) {
this.encoderQRCode(content, output, imgType, 7);
}

/**
* 生成二维码(QRCode)图片
* @param content 存储内容
* @param imgPath 图片路径
* @param imgType 图片类型
* @param size 二维码尺寸
*/
public void encoderQRCode(String content, String imgPath, String imgType, int size) {
try {
BufferedImage bufImg = this.qRCodeCommon(content, imgType, size);

File imgFile = new File(imgPath);
// 生成二维码QRCode图片
ImageIO.write(bufImg, imgType, imgFile);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 生成二维码(QRCode)图片
* @param content 存储内容
* @param output 输出流
* @param imgType 图片类型
* @param size 二维码尺寸
*/
public void encoderQRCode(String content, OutputStream output, String imgType, int size) {
try {
BufferedImage bufImg = this.qRCodeCommon(content, imgType, size);
// 生成二维码QRCode图片
ImageIO.write(bufImg, imgType, output);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 生成二维码(QRCode)图片的公共方法
* @param content 存储内容
* @param imgType 图片类型
* @param size 二维码尺寸
* @return
*/
private BufferedImage qRCodeCommon(String content, String imgType, int size) {
BufferedImage bufImg = null;
try {
Qrcode qrcodeHandler = new Qrcode();
// 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
qrcodeHandler.setQrcodeErrorCorrect('M');
qrcodeHandler.setQrcodeEncodeMode('B');
// 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大
qrcodeHandler.setQrcodeVersion(size);
// 获得内容的字节数组,设置编码格式
byte[] contentBytes = content.getBytes("utf-8");
// 图片尺寸
int imgSize = 67 + 12 * (size - 1);
bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufImg.createGraphics();
// 设置背景颜色
gs.setBackground(Color.WHITE);
gs.clearRect(0, 0, imgSize, imgSize);

// 设定图像颜色> BLACK
gs.setColor(Color.BLACK);
// 设置偏移量,不设置可能导致解析出错
int pixoff = 2;
// 输出内容> 二维码
if (contentBytes.length > 0 && contentBytes.length < 800) {
boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
for (int i = 0; i < codeOut.length; i++) {
for (int j = 0; j < codeOut.length; j++) {
if (codeOut[j][i]) {
gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
}
}
}
} else {
throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");
}
gs.dispose();
bufImg.flush();
} catch (Exception e) {
e.printStackTrace();
}
return bufImg;
}

/**
* 解析二维码(QRCode)
* @param imgPath 图片路径
* @return
*/
public String decoderQRCode(String imgPath) {
// QRCode 二维码图片的文件
File imageFile = new File(imgPath);
BufferedImage bufImg = null;
String content = null;
try {
bufImg = ImageIO.read(imageFile);
QRCodeDecoder decoder = new QRCodeDecoder();
content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} catch (DecodingFailedException dfe) {
System.out.println("Error: " + dfe.getMessage());
dfe.printStackTrace();
}
return content;
}

/**
* 解析二维码(QRCode)
* @param input 输入流
* @return
*/
public String decoderQRCode(InputStream input) {
BufferedImage bufImg = null;
String content = null;
try {
bufImg = ImageIO.read(input);
QRCodeDecoder decoder = new QRCodeDecoder();
content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} catch (DecodingFailedException dfe) {
System.out.println("Error: " + dfe.getMessage());
dfe.printStackTrace();
}
return content;
}

public static void main(String[] args) {
String imgPath = "H:/123.jpg";
String encoderContent = "http://gst.asti.cn";
// String content="H:/1.jpg";
TwoDimensionCode handler = new TwoDimensionCode();
handler.encoderQRCode(encoderContent, imgPath, "png");
/* try {
OutputStream output = new FileOutputStream(imgPath);
handler.encoderQRCode(content, output);
} catch (Exception e) {
e.printStackTrace();
}*/
System.out.println("========encoder success");


String decoderContent = handler.decoderQRCode(imgPath);
System.out.println("解析结果如下:");
System.out.println(decoderContent);
System.out.println("========decoder success!!!");
}

}

 

1.3 TwoDimensionCodeImage.java 文件

 

package com.applet.another;
import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

public class TwoDimensionCodeImage implements QRCodeImage {

BufferedImage bufImg;

public TwoDimensionCodeImage(BufferedImage bufImg) {
this.bufImg = bufImg;
}

public int getHeight() {
return bufImg.getHeight();
}

public int getPixel(int x, int y) {
return bufImg.getRGB(x, y);
}

public int getWidth() {
return bufImg.getWidth();
}

}

 

 

 2、带logo的二维码生成,有4个文件:BufferedImageLuminanceSource.java,CreateAndShowEwmLogo.java,DecodePic.java,QRCodeUtil.java:

2.1 BufferedImageLuminanceSource.java 文件

package com.applet.another.logo;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import com.google.zxing.LuminanceSource;

public class BufferedImageLuminanceSource extends LuminanceSource {
private final BufferedImage image;
private final int left;
private final int top;

public BufferedImageLuminanceSource(BufferedImage image) {
this(image, 0, 0, image.getWidth(), image.getHeight());
}

public BufferedImageLuminanceSource(BufferedImage image, int left,
int top, int width, int height) {
super(width, height);

int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
if (left + width > sourceWidth || top + height > sourceHeight) {
throw new IllegalArgumentException(
"Crop rectangle does not fit within image data.");
}

for (int y = top; y < top + height; y++) {
for (int x = left; x < left + width; x++) {
if ((image.getRGB(x, y) & 0xFF000000) == 0) {
image.setRGB(x, y, 0xFFFFFFFF); // = white
}
}
}

this.image = new BufferedImage(sourceWidth, sourceHeight,
BufferedImage.TYPE_BYTE_GRAY);
this.image.getGraphics().drawImage(image, 0, 0, null);
this.left = left;
this.top = top;
}


public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException(
"Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
image.getRaster().getDataElements(left, top + y, width, 1, row);
return row;
}


public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
int area = width * height;
byte[] matrix = new byte[area];
image.getRaster().getDataElements(left, top, width, height, matrix);
return matrix;
}


public boolean isCropSupported() {
return true;
}


public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left,
this.top + top, width, height);
}


public boolean isRotateSupported() {
return true;
}


public LuminanceSource rotateCounterClockwise() {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0,
0.0, 0.0, sourceWidth);
BufferedImage rotatedImage = new BufferedImage(sourceHeight,
sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
int width = getWidth();
return new BufferedImageLuminanceSource(rotatedImage, top,
sourceWidth - (left + width), getHeight(), width);
}
}

 

2.2 CreateAndShowEwmLogo.java 文件

 

package com.applet.another.logo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CreateAndShowEwmLogo extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String _url=req.getParameter("_url");
String path="D:\\tomcat\\tomcat6.0.35\\webapps\\erweima";
try {
QRCodeUtil.encode(_url, "H:/1.gif", path, true,true,"logoImg");
} catch (Exception e) {
e.printStackTrace();
}
PrintWriter writer=resp.getWriter();
writer.write("logoImg.jpg");
if(null!=writer){
writer.close();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}

}

 

2.3 DecodePic.java 文件

 

package com.applet.another.logo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.applet.another.TwoDimensionCode;

public class DecodePic extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String path=req.getParameter("picPath");
PrintWriter writer=resp.getWriter();
/*
// 第一种方法
TwoDimensionCode handler = new TwoDimensionCode();
String decoderContent = handler.decoderQRCode(path);
writer.write(decoderContent);*/

// 第二种方法
try {
writer.write(QRCodeUtil.decode(path));
} catch (Exception e) {
e.printStackTrace();
}

if(null!=writer){
writer.close();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
}

 

2.4 QRCodeUtil.java 文件

 

package com.applet.another.logo;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
* 二维码工具类
*
*/
public class QRCodeUtil {

private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;

private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}

/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param imgPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}

/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存放目录
* @param needCompress
* 是否压缩LOGO
* @param needsOne
* 是否只生成1个二维码,true为1个,名称使用参数needsOneImgName指定;false为多个,名称用随机数
* @param needsOneImgName
* 只有一个二维码时,它的名称,仅当needsOne为true时,该值才有效
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath,
boolean needCompress,boolean needsOne,String needsOneImgName) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,needCompress);
mkdirs(destPath);
String file="";
if(needsOne){
file = needsOneImgName+".jpg";
}else{
file = new Random().nextInt(99999999)+".jpg";
}
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
}

/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
* @author lanyuan
* Email: [email protected]
* @date 2013-12-11 上午10:16:36
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}

/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath)
throws Exception {
QRCodeUtil.encode(content, imgPath, destPath, false,false,null);
}

/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String destPath,
boolean needCompress) throws Exception {
QRCodeUtil.encode(content, null, destPath, needCompress,false,null);
}

/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String destPath) throws Exception {
QRCodeUtil.encode(content, null, destPath, false,false,null);
}

/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param output
* 输出流
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}

/**
* 生成二维码
*
* @param content
* 内容
* @param output
* 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output)
throws Exception {
QRCodeUtil.encode(content, null, output, false);
}

/**
* 解析二维码
*
* @param file
* 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}

/**
* 解析二维码
*
* @param path
* 二维码图片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}

public static void main(String[] args) throws Exception {
String text = "https://www.baidu.com";
QRCodeUtil.encode(text, "H:/1.gif", "H:/", true,false,null);
}
}

 

3、web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 不带logo的二维码 -->
<servlet>
<servlet-name>createAndShow</servlet-name>
<servlet-class>com.applet.another.CreateAndShowEwm</servlet-class>
</servlet>
<!-- 带logo的二维码 -->
<servlet>
<servlet-name>createAndShowLogo</servlet-name>
<servlet-class>com.applet.another.logo.CreateAndShowEwmLogo</servlet-class>
</servlet>
<!-- 解析二维码图片 -->
<servlet>
<servlet-name>decodePic</servlet-name>
<servlet-class>com.applet.another.logo.DecodePic</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>createAndShow</servlet-name>
<url-pattern>/createAndShowEwm.ser</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>createAndShowLogo</servlet-name>
<url-pattern>/createAndShowEwmLogo.ser</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>decodePic</servlet-name>
<url-pattern>/decodePic.ser</url-pattern>
</servlet-mapping>
</web-app>

 

4、index.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>
<base href="<%=basePath%>">

<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>p,img{margin:0px;padding:0px;}</style>
<script type="text/javascript" src="<%=basePath%>js/jquery.min.js"></script>
</head>

<body>
<fieldset>
<legend>不带logo的二维码</legend>
<table>
<tr>
<td><a href="https://www.baidu.com" target="_blank">百度</a></td>
<td><input type="button" οnclick="createEwm(this)" value="生成二维码"/></td>
</tr>
<tr>
<td><a href="http://www.163.com" target="_blank">网易</a></td>
<td><input type="button" οnclick="createEwm(this)" value="生成二维码"/></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>带logo的二维码</legend>
<table>
<tr>
<td><a href="https://www.baidu.com" target="_blank">百度</a></td>
<td><input type="button" οnclick="createEwmLogo(this)" value="生成二维码"/></td>
</tr>
<tr>
<td><a href="http://www.163.com" target="_blank">网易</a></td>
<td><input type="button" οnclick="createEwmLogo(this)" value="生成二维码"/></td>
</tr>
</table>
</fieldset>
<div style="border:1px solid black;text-align:center;display:none;width:200px;height:200px;position:absolute;left:180px;top:28px;z-index:999;background-color:white;" id="mb" ></div>
选择二维码所在路径:<input type="file" id="picPath"/><input type="button" οnclick="decodePic()" value="解析二维码内容"/>
<div id="picText"></div>
<script type="text/javascript">
$(function(){});
function createEwm(e){
$("#mb").css("display","block").text("正在生成,请稍等。。");
$.ajax({
type:"post",
data:{
_url:$(e).parent().parent().find("td:eq(0)").find("a:eq(0)").attr("href")
},
url:"<%=basePath %>createAndShowEwm.ser",
success:function(data){
$("#mb").css("display","block").html("<p style='margin-top:10px;'>"+$(e).parent().parent().find("td:eq(0)").find("a:eq(0)").text()+":</p>").append("<img src='<%=basePath %>"+data+"' style='width:150px;height:150px;margin-top:20px;'/>");
},error:function(e){
alert(e);
}
});
}
function createEwmLogo(e){
$("#mb").css("display","block").text("正在生成,请稍等。。");
$.ajax({
type:"post",
data:{
_url:$(e).parent().parent().find("td:eq(0)").find("a:eq(0)").attr("href")
},
url:"<%=basePath %>createAndShowEwmLogo.ser",
success:function(data){
$("#mb").css("display","block").html("<p style='margin-top:10px;'>"+$(e).parent().parent().find("td:eq(0)").find("a:eq(0)").text()+":</p>").append("<img src='<%=basePath %>"+data+"' style='width:150px;height:150px;margin-top:20px;'/>");
},error:function(e){
alert(e);
}
});
}
function decodePic(){
var path=$("#picPath").val();
if(path){
$("#picText").text("正在解析..");
$.ajax({
type:"post",
url:"decodePic.ser",
data:{
picPath : path
},
success:function(data){
$("#picText").text(data);
},error:function(e){
alert(e);
}
});
}
}
</script>
</body>
</html>

 

走起来!!成功,截图:

带logo图片或不带logo图片的二维码生成与解析,亲测成功

 

带logo图片或不带logo图片的二维码生成与解析,亲测成功

 

带logo图片或不带logo图片的二维码生成与解析,亲测成功

 

带logo图片或不带logo图片的二维码生成与解析,亲测成功

 

如果你有更好的方法,望不吝赐教,^_^