图片新增水印
给网页图片添加水印是个常见的功能,也是互联网内容作者保护自己版权的方法之一。本文简单记录一下借助canvas在前端实现图片添加水印的实现方法。
canvas元素其实就是一个画布,我们可以很方便地绘制一些文字、线条、图形等,它也可以将一个img标签里渲染的图片画在画布上。
const img: any = new Image();
img.src =
'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp2-q.mafengwo.net%2Fs11%2FM00%2FB6%2F7B%2FwKgBEFt_tvGAFvHxAAFIRKQnOBw21.jpeg&refer=http%3A%2F%2Fp2-q.mafengwo.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1658649916&t=6270eb9f963c25eb9af5cc101fe42e38';
img.crossOrigin = 'anonymous';
img.onload = function () {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx: any = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
ctx.font = '100px 宋体';
ctx.fillStyle = 'rgba(255, 255, 255)';
ctx.fillText('前端同学出品', img.width - 500, img.height - 50, 500); //文本 距离左上角位置,允许最大像素
const base64Url = canvas.toDataURL();
let result = new Image();
result.width = 300;
result.height = 300;
result.src = base64Url;
document.body.appendChild(result);
console.log(base64Url);
console.log(base64toBlob(base64Url));
console.log(translateBase64ImgToBlob(base64Url, 'image/jpeg'));
};
/*
Base64 转成 Blob
*/
function base64toBlob(dataurl: any) {
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 });
}
/*
Bolb 转 URL
原理: 利用URL.createObjectURL为blob对象创建临时的URL
*/
function translateBase64ImgToBlob(base64: any, contentType: any) {
var arr = base64.split(','); //去掉base64格式图片的头部
var bstr = atob(arr[1]); //atob()方法将数据解码
var leng = bstr.length;
var u8arr = new Uint8Array(leng);
while (leng--) {
u8arr[leng] = bstr.charCodeAt(leng); //返回指定位置的字符的 Unicode 编码
}
var blob = new Blob([u8arr], { type: contentType });
var blobImg: any = {};
blobImg.url = URL.createObjectURL(blob); //创建URL
blobImg.name = new Date().getTime() + '.png';
return blobImg;
}
这样就完整地给图片添加了水印效果,
# 新增页面水印
/** 水印添加方法 */
const setWatermark = (str1, str2) => {
const id = '1123412415'
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
const can = document.createElement('canvas')
// 设置canvas画布大小
can.width = 240
can.height = 140
const cans = can.getContext('2d')
cans.rotate(-25 * Math.PI / 180) // 水印旋转角度
cans.font = '1.2rem Vedana'
cans.fillStyle = '#666'
cans.textAlign = 'center'
cans.textBaseline = 'Middle'
cans.fillText(str1, can.width / 2, can.height) // 水印在画布的位置x,y轴
cans.fillText(str2, can.width / 2, can.height + 25)
const div = document.createElement('div')
div.id = id
div.style.pointerEvents = 'none'
div.style.top = '20px'
div.style.left = '0px'
div.style.opacity = '0.2'
div.style.position = 'fixed'
div.style.zIndex = '100000'
div.style.width = document.documentElement.clientWidth + 'px'
div.style.height = document.documentElement.clientHeight + 'px'
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
document.body.appendChild(div)
return id
}