我是靠谱客的博主 优美耳机,最近开发中收集的这篇文章主要介绍图片添加水印,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

const base = {}
/**
* @description: 图片添加水印
* @param {file} file 图片的file对象
* @param {Function} callback 因为onload异步的问题 所以采用callback方式
*/
base.watermark = (file, callback) => {
if (!file || !file.name) return false
let fileReader = new FileReader()
fileReader.readAsDataURL(file)
let img = new Image()
fileReader.onload = function () {
img.src = fileReader.result
img.onload = function () {
// 创建canvas进行绘图
const canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d')
canvas.width = img.width
canvas.height = img.height
// 首先绘制需要上传至服务器的图
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
const text = '水印的文字'
const foneSize = Math.min(Math.round((30 * img.width) / 350), 60) // 按图片宽度适当设置字号,最大60
ctx.font = `${foneSize}px Microsoft Yahei`
;(ctx.fillStyle = 'rgba(0,125,255,0.1)'), (ctx.textBaseline = 'bottom')
ctx.rotate((Math.PI / 180) * 15)
const textWidth = ctx.measureText(text).width // 预估文字绘制后占的宽度
for (let i = img.width * -0.5; i < img.width * 1.5; i += textWidth * 1.4) {
for (let j = img.height * -0.5; j < img.height * 1.5; j += foneSize * 2) {
ctx.fillText(text, i, j)
}
}
// 转为base64格式
let imgData = canvas.toDataURL(file.type)
// 转为file对象传递出去
callback(dataURLtoFile(imgData, file.name), imgData)
}
}
}
// 将base64转换为文件
function dataURLtoFile(dataurl, filename) {
let 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 File([u8arr], filename, { type: mime })
}
export default base

最后

以上就是优美耳机为你收集整理的图片添加水印的全部内容,希望文章能够帮你解决图片添加水印所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部