使用谷歌zxing包生成二维码
程序员文章站
2022-06-04 16:22:13
...
使用谷歌Zxing包生成二维码
一、环境 (springboot项目中)
二、引包
pop.xml文件中引入以下两个包
<!-- json数据转化 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.0</version>
</dependency>
三、代码
imageZxing.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>My JSP 'imageZxing.jsp' starting page</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">
-->
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
</head>
<body>
<div>
<div id="ewm" style="width:300px;height:300px;border:1px blue solid;">
</div>
<button id="scewm" onclick="CreatEWM();">生成二维码</button>
</div>
</body>
<script>
function CreatEWM(){
$("#ewm").html("");
var params = {};
params.cs = "ewm";
var paramsJson = JSON.stringify(params);
$.ajax({
type:"POST",
url:"/getPng",
dataType:"json",
async:false,
data:{
"params":paramsJson
},
success:function(result){
var image = result.obj.ewm;
var url = "data:image/gif;base64,"+image;
var html = "<img src='"+url+"' />";
$("#ewm").append(html);
},
error:function(){
alert("生成二维码失败");
}
});
}
</script>
</html>
2.CreatEWMController
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.dcits.common.ResultJson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.misc.BASE64Encoder;
@Controller
public class CreatEWMController {
@RequestMapping("/ewm")
public String CreatEWM(){
return "imageZxing";
}
@RequestMapping("/getPng")
@ResponseBody
public ResultJson getPng(HttpServletRequest request,HttpServletResponse response) throws Exception{
Map<String,Object> params = JSON.parseObject(request.getParameter("params")); //接收前台传过来的参数
String cs = String.valueOf(params.get("cs"));
ResultJson result = new ResultJson();
Map map = new HashMap();
//二维码内容拼装示例
String wzewmnr = "http://www.baidu.com";
//二维码参数设置
Map<EncodeHintType,Object> config = new HashMap<EncodeHintType,Object>();
config.put(EncodeHintType.CHARACTER_SET,"UTF-8"); //二维码编码格式
config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //纠错
config.put(EncodeHintType.MARGIN, 2); //二维码周围空白距离
//设置二维码前景色、背景色
MatrixToImageConfig con = new MatrixToImageConfig(0xFF000002, 0xFFFFFFFF);
//生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(wzewmnr, BarcodeFormat.QR_CODE,300,300,config);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix,con);
//添加logo标志
Graphics2D gs = image.createGraphics();
//new ClassPathResource("D:/fengye.jpg").getFile()
BufferedImage logo = ImageIO.read(new ClassPathResource("/static/images/gsj.jpg").getFile()); //rosources下
int widthLogo = logo.getWidth(null) > image.getWidth() * 3 / 10 ? (image.getWidth() * 3 / 10)
: logo.getWidth(null),
heightLogo = logo.getHeight(null) > image.getHeight() * 3 / 10 ? (image.getHeight() * 3 / 10)
: logo.getWidth(null);
//设置logo居中
int x = (image.getWidth() - widthLogo) / 2;
int y = (image.getHeight() - heightLogo) / 2;
// 开始绘制图片
gs.drawImage(logo, x, y, widthLogo, heightLogo, null);
gs.setColor(Color.YELLOW);
gs.setBackground(Color.WHITE);
gs.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。
ImageIO.write(image, "png", os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。
byte b[] = os.toByteArray();//从流中获取数据数组。
String str = new BASE64Encoder().encode(b);
map.put("ewm",str);
result.setObj(map);
result.setMsg("生成成功!");
result.setSuccess(true);
return result;
}
3.ResultJson类
import java.io.Serializable;
public class ResultJson implements Serializable {
public static final int SUCCESS = 1;
public static final int FAILURE = -1;
private static final long serialVersionUID = 5576237395711742681L;
private boolean success = false;
private String msg = "";
private Object obj = null;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
上一篇: 新生儿肺炎如何产生 或产前感染性肺炎