nodejs本身不太擅长处理图片视频等计算密集性的功能,所以需要第三方的非nodejs库或工具来实现此功能。
这里就使用了多媒体处理开源库ffmpeg,其中的drawtext滤镜就可以高效的实现图片添加文字水印功能。drawtext滤镜详细文档在这里可以查看 https://ffmpeg.org/ffmpeg-filters.html#drawtext-1
详细代码如下
import execcmd from 'child_process'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'node:url'
import { stderr, stdout } from 'process'
import util from 'util'
const exec = util.promisify(execcmd.exec)
let curDir = fileURLToPath(new URL('./', import.meta.url))
let picFile = "test.jpg"
let processedPicFile = "processedtest.jpg"
var cmdstr = "ffmpeg -i " + picFile
cmdstr += " -vf \"drawtext=fontfile=./tmp/msyhbd.ttc:fontsize=16:x=(w - 10 - text_w):y=10:fontcolor=white:text='凸然(tr.zhiyakeji.com)':shadowx=4:shadowy=4:alpha=0.5\""
cmdstr += " -y " + processedPicFile
const { stdout, stderr } = await exec(cmdstr)
console.error(stderr)
上面主要是通过nodejs的命令行执行工具类import execcmd from 'child_process'
来执行ffmpeg命令来添加水印。
相关命令行参数解释如下:
c:/Windows/Fonts
目录中的冒号处理有问题,导致始终提示找不到字体,从而文字为中文时会是乱码。w表示图片宽度
, text_w表示的是文字的宽度
shadowcolor
来设置。