图片上传大家都不会陌生,就算是一个新人也会干的事儿。但说到加水印,当初我一直以为只能是在后端实现。
原来,在前端也是能实现图片上传加水印的。(注:以下的代码都来自于网络,只是我把两部份代码合在一起来实现我的需求而已,在最后面,我也会附上原作者的接,大家都不容易)
【注:我自己写的注释后面会有个"(小冰)",其他的为原作者的注释】
<van-uploader v-model="filelist" multiple:after-read="afterread"/>
data(){ filelist:[], //vant中图片上传的双向邦定(小冰) wmconfig : { //用于水印的东西,下面会用到 (小冰) font: "microsoft yahei", //字体 textarray: ['张三','2021/11/26 16:44'],//水印文本内容,允许数组最大长度3 即:3行水印 density: 3 //密度 建议取值范围1-5 值越大,水印越多,可能会导致水印重叠等问题,慎重!!! } }
methods:{ //dataurltoblob 、 blobtofile 两个方法的意思是把base64的图片转换成file文件 //1,先将base64转换为blob dataurltoblob(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new uint8array(n); while (n--) { u8arr[n] = bstr.charcodeat(n); } return new blob([u8arr], { type: mime }); }, //2,再将blob转换为file blobtofile(theblob, filename){ theblob.lastmodifieddate = new date(); // 文件最后的修改日期 theblob.name = filename; // 文件名 return new file([theblob], filename, {type: theblob.type, lastmodified: date.now()}); }, //这个不多说,都懂,文件上传的方法(小冰) async afterread(file){ console.log(file) let base64 = file.content; let res = await this.base64addwatermaker(base64,this.wmconfig) //加水印的重点就是这个(小冰) file.content = res; let blob = this.dataurltoblob(file.content); // 拿到文件名 let filename = file.file.name; // 2,在转为 file类型 let file1 = this.blobtofile(blob,filename); console.log("file1:",file1); }, base64addwatermaker (base64img, wmconfig) { let that = this; if (wmconfig.textarray.length === 0) { console.error("****没有水印内容*****"); return base64img; } return new promise((resolve, reject) => { const canvas = document.createelement("canvas"); const ctx = canvas.getcontext("2d"); const img = new image(); let resultbase64 = null; img.onload = function() { canvas.width = img.width; canvas.height = img.height; //canvas绘制图片,0 0 为左上角坐标原点 ctx.drawimage(img, 0, 0); //写入水印 that.drawwatermark(ctx, img.width, img.height, wmconfig); resultbase64 = canvas.todataurl("image/png"); if (!resultbase64) { reject(); } else { resolve(resultbase64); } }; img.src = base64img; }); }, drawwatermark (ctx, imgwidth, imgheight, wmconfig) { let fontsize; if (imgwidth >= 3456) { fontsize = 50; } else if (imgwidth >= 2700) { fontsize = 30; } else if (imgwidth >= 2000) { fontsize = 26; } else if (imgwidth >= 1436) { fontsize = 20; } else if (imgwidth >= 800) { fontsize = 12; } else if (imgwidth >= 500) { fontsize = 10; } else { fontsize = 8; } console.log(imgwidth, imgheight, fontsize); ctx.fillstyle = "white"; ctx.font = `${fontsize}px ${wmconfig.font}`; ctx.linewidth = 1; ctx.fillstyle = "rgba(255,255,255,1)"; ctx.textalign = "left"; ctx.textbaseline = "middle"; //文字坐标 const maxpx = math.max(imgwidth, imgheight); const steppx = math.floor(maxpx / wmconfig.density); let arrayx = [0];//初始水印位置 canvas坐标 0 0 点 while (arrayx[arrayx.length - 1] < maxpx/2) { arrayx.push(arrayx[arrayx.length - 1] + steppx); } arrayx.push(...arrayx.slice(1, arrayx.length).map((el) => { return -el; })); console.log(arrayx); for (let i = 0; i < arrayx.length; i++) { for (let j = 0; j < arrayx.length; j++) { ctx.save(); ctx.translate(imgwidth / 2, imgheight / 2); ///画布旋转原点 移到 图片中心 ctx.rotate(-math.pi / 5); if (wmconfig.textarray.length > 3) { wmconfig.textarray = wmconfig.textarray.slice(0, 3); } wmconfig.textarray.foreach((el, index) => { let offsety = fontsize * index + 2; ctx.filltext(el, arrayx[i], arrayx[j] + offsety); }); ctx.restore(); } } } }
代码就是这些,然而,在此中,我是把图片加水印和图片base64转file两个不同的博文混在一起写的。
图片加水印 :javascript实现为图片添加水印的方法
base64转file:js中将图片base64转file文件的两种方式
顺便我也把file文件转base64的封装函数也发一下。当然,这个我也是在网上找的。
function filetobase64(file, callback) { //callback 是一个回调函数,而回调函数往这儿走一回,它结果就是base64 const filereader = new filereader() filereader.readasdataurl(file) filereader.onload = function () { callback(this.result) } }, function callbasefun(res){ console.log(res,'res打印出来就是base64') },
//---------------------------分割线--------------------
第二种方法,跟上面的方法差不多,只是这种方法可以随意去调整水印的位置和大小什么的。
//将base64转化为二进制 datauritoblob(base64data) { var date = new date(); //console.log('将base64转化为二进制', date.getminutes(), date.getseconds()) var bytestring; if (base64data.split(',')[0].indexof('base64') >= 0) bytestring = atob(base64data.split(',')[1]); else bytestring = unescape(base64data.split(',')[1]); var mimestring = base64data.split(',')[0].split(':')[1].split(';')[0]; var ia = new uint8array(bytestring.length); for (var i = 0; i < bytestring.length; i++) { ia[i] = bytestring.charcodeat(i); } return new blob([ia], { type: mimestring }); }, //将base64转化为二进制 datauritoblob(base64data) { var date = new date(); //console.log('将base64转化为二进制', date.getminutes(), date.getseconds()) var bytestring; if (base64data.split(',')[0].indexof('base64') >= 0) bytestring = atob(base64data.split(',')[1]); else bytestring = unescape(base64data.split(',')[1]); var mimestring = base64data.split(',')[0].split(':')[1].split(';')[0]; var ia = new uint8array(bytestring.length); for (var i = 0; i < bytestring.length; i++) { ia[i] = bytestring.charcodeat(i); } return new blob([ia], { type: mimestring }); }, //base64转canvas async imgtocanvas(base64) { var date = new date(); //console.log('base64转canvas', date.getminutes(), date.getseconds()) // 创建img元素 const img = document.createelement('img') img.setattribute('src', base64) await new promise((resolve) => (img.onload = resolve)) // 创建canvas dom元素,并设置其宽高和图片一样 const canvas = document.createelement('canvas') //console.log(img.height) //console.log(img.width) canvas.width = img.width canvas.height = img.height // 坐标(0,0) 表示从此处开始绘制,相当于偏移。 canvas.getcontext('2d').drawimage(img, 0, 0) return canvas }, //写入水印 addwatermark(canvas, txt1, txt2, txt3, tex4) { //alert(canvas.height) var date = new date(); //console.log('写入水印', date.getminutes(), date.getseconds()) const ctx = canvas.getcontext('2d') //ctx.font = '50px arial' //ctx.stroketext(text, 0, 0) ctx.font = '20px arial' ctx.fillstyle = 'white' ctx.filltext(txt1, 20, canvas.height - 240) ctx.filltext(txt2, 20, canvas.height - 200) ctx.filltext(txt3, 20, canvas.height - 160) ctx.filltext(tex4, 20, canvas.height - 120) ctx.filltext(tex4, 20, canvas.height - 80) return canvas }, //canvas转图片文件(image) convastoimg(canvas) { var date = new date(); //console.log('canvas转图片文件(image)', date.getminutes(), date.getseconds()) // 新建image对象,可以理解为dom let image = new image() // canvas.todataurl 返回的是一串base64编码的url // 指定格式 png image.src = canvas.todataurl('image/png') return image }, //图片文件(image)转文件(file) base64tofile(urldata, filename) { var date = new date(); //console.log('图片文件(image)转文件(file)', date.getminutes(), date.getseconds()) let arr = urldata.split(','); let mime = arr[0].match(/:(.*?);/)[1]; let bytes = atob(arr[1]); // 解码base64 let n = bytes.length let ia = new uint8array(n); while (n--) { ia[n] = bytes.charcodeat(n); } return new file([ia], filename, { type: mime }); }, //file对象转base64 filetobase64(file, callback) { //callback 是一个回调函数,而回调函数往这儿走一回,它结果就是base64 var date = new date(); //console.log('file对象转base64', date.getminutes(), date.getseconds()) return new promise((resolve, reject) => { const filereader = new filereader() filereader.readasdataurl(file) filereader.onload = function () { let res = callback(this.result) resolve(res) } }) }, callbasefun(res) { //console.log('上传的方法') return new promise((resolve, reject) => { let that = this; //console.log(res, 'base64') let str = res.split(','); str[0] = 'data:image/jpeg;base64'; let r = str.tostring(); let url = "/serverapi/serverbase64api.ashx" var obj = { imgbase64: r, method: "serverbase64png", module: "daka", id: "a4e89358-9465-4295-87ea-4d0af2bd9133" } jquery.ajax({ url: url, type: 'post', data: obj, datatype: 'json', timeout: 8000, }) .done(res => { var date = new date(); //console.log('上传成功', date.getminutes(), date.getseconds()) //console.log('成功时执行') resolve(res) }) .fail(err => { //console.log(err, '上传失败') reject({ msg: '上传失败' }) }) }) },
async oneupload(e){ let base64 = e.content; let tempcanvas = await this.imgtocanvas(base64) //得到canvas的值 const canvas = this.addwatermark(tempcanvas , '水印1' , '水印2' , '水印3'); //这儿水印的参数是根据 addwatermark()方法里面的 ctx.filltext(txt1, 20, canvas.height - 240) 进行修改 const img = this.convastoimg(canvas); //canvas转图片文件(image) let newfile = this.base64tofile(img.src) //图片文件转file对象 let res = await this.filetobase64(newfile, this.callbasefun) //file转base64, 注意 第二个参数是一个回调函数,也就是说回调函数里面的参数就是base64的值 }
到此这篇关于vue+vant实现图片上传添加水印的文章就介绍到这了,更多相关vue vant图片加水印内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论