在最近 haoyo择校 功能中,需要上传各个高校的招生计划图片;为申明版权,故需要在上传图片时添加水印。
技术栈:
vue2.x +element-ui +more...
实现思路:
- 利用?
element-ui ?的?upload ?组件,监听http-request 事件,获取到上传的文件信息。 - 将获取到的文件信息file, 转为base64格式。
- 将base64格式的图片转为canvas格式,并获取到canvas的图片对象。
- 给canvas图层添加水印。
- 将canvas图层转为图片格式(.jpg, .png….)。
- 将图片转为文件格式去上传。
代码示例:
入口方法
beforeUpload(file) {
console.log(file)
return new Promise((resolve, reject) => {
this.fileByBase64(file, async (base64) => {
let tempCanvas = await this.imgToCanvas(base64)
const canvas = this.addWatermark(tempCanvas, '考研公众号:HaoYo')
const img = this.convasToImg(canvas, file.type)
let newFile = this.base64ToFile(img.src, file.name)
resolve(newFile)
})
})
},
文件转base64
fileByBase64(file, callback){
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
callback(e.target.result)
};
},
Base64转成canvas
async imgToCanvas(base64) {
const img = document.createElement('img')
img.setAttribute('src', base64)
await new Promise((resolve) => (img.onload = resolve))
const canvas = document.createElement('canvas')
console.log(img.height)
console.log(img.width)
canvas.width = img.width
canvas.height = img.height
canvas.getContext('2d').drawImage(img, 0, 0)
return canvas
},
给canvas添加水印
addWatermark(canvas, text) {
const ctx = canvas.getContext('2d')
ctx.fillStyle = '#aaa'
ctx.textBaseline = 'middle'
ctx.font = (ctx.canvas.width / 20) + 'px Arial'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(text, canvas.width / 2, canvas.height / 2)
return canvas
},
canvas转成img
convasToImg(canvas, type) {
let image = new Image()
image.src = canvas.toDataURL(type)
return image
},
将img图片转为file类型的文件(用于上传)
base64ToFile(urlData, fileName) {
let arr = urlData.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]);
let n = bytes.length
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
return new File([ia], fileName, { type: mime });
},
最后图片,就开开心心的被加上水印了呀~
created_at:zhanghaoran’s blog 2022-04-27
原文地址:https://blog.zhanghaoran.ren/article/html/QianDuanShangChuanTuPianTianJiaShuiYin.html
|