javascript - 获取目录中的所有图像,在图像上键入每个图像的文件名
问题描述
我想确定一个目录“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 (我还不能添加图片)
解决方案
尝试这个
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
声明在这里可能很关键。
推荐阅读
- c - 开关/案例无法识别某些字符输入
- java - 无法实例化 Worker
- javascript - 在vue中同时点击元素
- java - JAVA中的正则表达式制作密码
- html - 如何使用网格 CSS 固定块外套、连身衣、服装和连衣裙?
- c - 在 C 中的 CHAR 之后存储 INT 需要 7 个字节而不是 4 个
- c# - 无法将“System.Web.Mvc.ReflectedActionDescriptor”类型的对象转换为“System.Web.Mvc.Async.TaskAsyncActionDescriptor”类型
- python - “OneSidedSelection”方法是“CondensedNearestNeighbour”和“Tomek Links”方法的组合吗?
- html - Bootstrap crousell 响应式大小调整
- python - 有没有办法使用 Sympy 在 Python 中的点 (x,y) 评估多元函数