在Nodejs中使用jimp给图片添加文字水印

效果图

效果描述

在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

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值