效果图
效果描述
在nodejs中使用multer上传图片之后,使用jimp给图片添加文字水印,文字水印的大小是根据图片的宽高进行灵活设置,以防文字过大或过小导致不和谐。
代码实现
const ShopService = require("../../services/admin/ShopService");
const fs = require('fs')
const path = require('path')
const Jimp = require('jimp')
const shopController = {
// 更新店铺信息
update: async (req, res) => {
const { phone, shopName, password, service, serviceContent, shopIntroduce, address, shopType, shopPicsString } = req.body
const shopPics = req.files.length ? req.files.map(item => `/shopPics/${item.filename}`) : ''
const latLng = await getLatLng(address);
let lngAndlat = {}
if (latLng) {
lngAndlat.lng = latLng.lng
lngAndlat.lat = latLng.lat
}
// 如果有新的图片上传,则添加水印
if (shopPics.length > 0) {
await Promise.all(shopPics.map(async (picPath) => {
await addWatermark(path.join(__dirname, '../../public', picPath));
}));
}
const result = await ShopService.update({ phone, shopName, password, service, serviceContent, shopIntroduce, address, shopType, shopPics, shopPicsString: JSON.parse(shopPicsString), lngAndlat: JSON.stringify(lngAndlat), location: { type: 'Point', coordinates: [latLng.lng, latLng.lat] } })
res.send({
msg: 'ok',
data: result
})
},
}
// 封装添加文字水印到图片右下角的函数
async function addWatermark(inputPath) {
try {
// 读取原始图片
const image = await Jimp.read(inputPath);
// 设置水印文本
const watermarkText = '© housekeeping';
// 创建一个透明背景的文字图层
const watermark = new Jimp(image.bitmap.width, image.bitmap.height, 0x00000000); // 0x00000000 表示完全透明
// 根据图片的宽度计算字体大小
const fontSize = Math.min(32, Math.max(16, Math.round(image.bitmap.width * 0.05)));
// 加载字体
const font = await Jimp.loadFont(Jimp[`FONT_SANS_${fontSize}_BLACK`]); // 字体大小和颜色
// 设置水印的位置
const textWidth = Jimp.measureText(font, watermarkText);
const textHeight = Jimp.measureTextHeight(font, watermarkText);
const x = image.bitmap.width - textWidth;
const y = image.bitmap.height - textHeight;
// 在透明图层上添加文字
watermark.print(font, x, y, watermarkText);
// 将文字图层叠加到原始图片上
image.composite(watermark, 0, 0);
// 保存带有水印的新图片
const outputDir = path.join(__dirname, '..', '..', 'public', 'watermarkShopPics');
const outputPath = path.join(outputDir, path.basename(inputPath));
await image.writeAsync(outputPath);
console.log(`Watermarked image saved to ${outputPath}`);
} catch (error) {
console.error('Error adding watermark:', error);
}
}
module.exports = ShopController