You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js的Jimp库为图片添加居中的两行文本?

用Jimp实现两行文本居中(含动态用户名)的解决方案

嘿,我来帮你搞定这个文本居中的问题!要在Jimp里实现两行居中的文本(尤其是最后一行是长度不固定的用户名),核心思路是先计算每一行文本的宽度,再结合图片宽度算出居中的X坐标——因为Jimp的print方法默认从左上角开始绘制,所以得手动计算偏移量。

核心步骤说明

  • 用Jimp.measureText()获取指定字体下文本的像素宽度,这是实现动态居中的关键
  • 水平居中公式:(图片宽度 - 文本宽度) / 2
  • 垂直方向通过字体行高和自定义间距来控制两行文本的位置,也可以轻松实现垂直居中

修改后的完整可运行代码

Jimp.read("./imgs/background.png").then(function (image) {
  // 固定图片尺寸为你需要的500px×167px
  image.resize(500, 167)
       .quality(100);

  Jimp.loadFont(Jimp.FONT_SANS_32_WHITE).then(function (font) {
    const imgWidth = image.bitmap.width;
    const imgHeight = image.bitmap.height;
    const line1Text = "Welcome";
    const username = "你的动态用户名"; // 这里替换为实际的动态用户名变量
    const lineHeight = font.common.lineHeight; // 获取字体默认行高,适配不同字体
    const lineSpacing = 10; // 两行文本之间的额外间距,可按需调整

    // --- 计算第一行文本的居中坐标 ---
    const line1Width = Jimp.measureText(font, line1Text);
    const line1X = (imgWidth - line1Width) / 2;
    // 如果需要垂直完全居中,把下面的line1Y改成注释里的公式
    const line1Y = 20; // 手动设置顶部偏移,或者用:(imgHeight - (lineHeight * 2 + lineSpacing)) / 2

    // --- 计算第二行(用户名)的居中坐标 ---
    const usernameWidth = Jimp.measureText(font, username);
    const usernameX = (imgWidth - usernameWidth) / 2;
    const usernameY = line1Y + lineHeight + lineSpacing;

    // 绘制两行文本
    image.print(font, line1X, line1Y, line1Text);
    image.print(font, usernameX, usernameY, username);

    // 最终保存图片
    image.write("./imgs/background-test.png", (err) => {
      if (err) console.error("图片保存失败:", err);
      else console.log("带居中文本的图片生成成功!");
    });
  });
}).catch(function (err) {
  console.error("图片/字体加载失败:", err);
});

额外优化提示

  1. 垂直完全居中:如果希望两行文本在整个图片中垂直居中,把line1Y替换成下面的代码:
const totalTextBlockHeight = lineHeight * 2 + lineSpacing;
const line1Y = (imgHeight - totalTextBlockHeight) / 2;
  1. 长用户名换行:如果用户名可能过长,可以在print方法里添加最大宽度参数,超出会自动换行:
image.print(font, usernameX, usernameY, {
  text: username,
  alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
  alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE
}, imgWidth - 40); // 左右留40px边距
  1. 避免重复加载:如果多次生成图片,建议把字体加载逻辑抽出来,避免重复加载提升性能。

内容的提问来源于stack exchange,提问作者Johny Deep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:40:07