首页 > 解决方案 > 获取目录中的所有图像,在图像上键入每个图像的文件名

问题描述

我想确定一个目录“inbox_screenshots”,其中包含从 1 到 100 的最多 100 个 png 文件的列表。我想遍历每个图像并将其文件名写入实际图像(即 1.png 写入 1.png 等)

我努力了

for (i = 1; i < 100; i++) {
  let fname = path + i + ".png"
  fs.access(fname, (err) => {
    if (err) {
      console.log("The file does not exist.");
    } else {
      console.log("The file exists.");
      Jimp.read(fname)
        .then(function (image) {
          loadedImage = image;
          return Jimp.loadFont(Jimp.FONT_SANS_128_BLACK);
        })
        .then(function (font) {
          loadedImage.print(font, 900, 100, i)
            .write(fname);
        })
        .catch(function (err) {
          console.error(err);
        });
    }
  });
}

运行此操作后,所有图像都输入了 100 个,而不是 1、2、3、4、5 等(文件名是 1.png->100.png)

我也试过

fs.readdirSync(path).forEach(file => {
    console.log(file);
    Jimp.read(path + file)
        .then(function (image) {
            loadedImage = image;
            return Jimp.loadFont(Jimp.FONT_SANS_128_BLACK);
        })
        .then(function (font) {
            loadedImage.print(font, 900, 100, file)
                .write(path + file);
        })
        .catch(function (err) {
            console.error(err);
        });
});

这适用于将文件名写入图像,但它将所有文件名写入每个图像,重叠,因此每个图像上都会有 1,2,3,4,5,6,7,8,9 等,重叠。

会欣赏正确方向的一点。

编辑我在第一个例子中错过了一个让

现在,当我添加它时,它会将文件名放在图像上,但它会不断将最后一个文件名堆叠在上面,例如,第 6 次迭代将有 1、2、3、4、5、6,而不仅仅是 6。这是一个例子:https ://i.gyazo.com/1c29db37dc564c75f78a696ca46cfc80.png (我还不能添加图片)

标签: javascriptnode.jsjimp

解决方案


尝试这个

for (let i = 1; i < 100; i++) {
  let fname = path + i + ".png"
  fs.access(fname, (err) => {
    if (err) {
      console.log("The file does not exist.");
    } else {
      console.log("The file exists.");
      Jimp.read(fname)
        .then(function (image) {
          loadedImage = image;
          return Jimp.loadFont(Jimp.FONT_SANS_128_BLACK);
        })
        .then(function (font) {
          console.log("writing to file: ", i);
          loadedImage.print(font, 900, 100, i)
            .write(fname);
        })
        .catch(function (err) {
          console.error(err);
        });
    }
  });
}

let i声明在这里可能很关键。


推荐阅读