1.调用jSignature插件生成手写数字签名
头部记得先引用jquery,再引用jSignature的js文件,html网页源码如下:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>signature_demo</title><script src="/jquery/1.10.2/jquery.min.js"></script><script src="../../js/jSignature.min.js"></script><!-- <script src="../../js/jquery.js"></script>--><!-- <script src="../../js/jSignature.js"></script>--><style type="text/css">#signature{position: absolute;border: 5px solid red;width: 90%;height: 45%;left: 5%;top: 25%;}.clearBtn{position: absolute;width: 20%;height: 10%;left: 25%;top: 80%;}.saveBtn{position: absolute;width: 20%;height: 10%;left: 55%;top: 80%;}</style><script type="text/javascript">//初始化画布$(document).ready(function(){$("#signature").jSignature({width:"100%",height:"100%",color:"#000",lineWidth:4});});//重置画布function clearSig(){$("#signature").jSignature("reset");}//将画布内容保存为base64编码字符串function saveImg(){if( $("#signature").jSignature('getData', 'native').length === 0){alert("请签名后再提交!");return;}var con=confirm("提交后不可更改,确认提交签名?");if(con===false) return;//保存将签名的画布保存为base64编码字符串var sig=$("#signature");var datapair=sig.jSignature("getData","image");// $("#img").attr("src","data:"+ datapair[0] + "," + datapair[1]);console.log(datapair[1]);// $("#img").attr("src","data:"+sig.jSignature('getData'));// console.log(sig.jSignature("getData"));//封装base64字符串,将其提交到后端var postData={};postData.imgStr=datapair[1];$.post("http://localhost:8099/SignatureSave",postData,function (data) {alert(data);})}</script></head><body><div id="signature"></div><button class="clearBtn" onclick="clearSig()">重置</button><button class="saveBtn" onclick="saveImg()">获取</button></body></html>
2.在后端接收到该base64字符串,再将其保存为图片存入本地
这里项目用的是springboot框架,源码如下
package com.main.activity.demo;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;import sun.misc.BASE64Decoder;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.UUID;/*** @author :* @description: TODO* @date :/10/10 19:53*/@RestControllerpublic class SignatureDemo {@PostMapping("/SignatureSave")public String SignatureSave(String imgStr) throws IOException {//使用uuid保证每次保存的图片名称唯一UUID uuid =UUID.randomUUID();//Base64解码,生成.png图片BASE64Decoder decoder = new BASE64Decoder();byte[] decoderBytes = decoder.decodeBuffer(imgStr);FileOutputStream out = new FileOutputStream(new File("E:/Desktop/Signature/"+uuid+".png"));out.write(decoderBytes);out.close();System.out.println(uuid);return "success";}}
这样签字的内容就保存到了本地的E:/Desktop/Signature文件夹下。
参考博文:
java实现base64字符串转换png图片
手写签名插件—jSignature使用心得
jSignature开发实例