我正在创建一个不和谐的机器人,但是我还是很新。我正在使用jimp
图像裁切器从URL获取图像,然后将其裁切为5个相同大小的片段。这是我的代码:
var Discord = require('discord.js');
var auth = require('./author.json');
var https = require('https');
var fs = require('fs');
var Jimp = require('jimp');
var bot = new Discord.Client({});
bot.login(auth.token);
bot.on('message', function(message, channelID, userID, user, evt) {
if (message.content.toString().includes(bot.user.toString())) {
message.channel.send("Use / instead")
}
if (message.content.toString() == "/ping") {
message.channel.send("pong")
}
if (message.attachments && message.content.toString().includes("/split")) {
Jimp.read(message.attachments.array()[0].url)
.then(image => {
for (var i = 0; i < 5; i++) {
return image
.clone().crop(0, image.bitmap.height / 5 * i, image.bitmap.width, image.bitmap.height / 5)
.write('./files/cropped' + i + '.png')
console.log(i);
}
})
.catch(err => {
console.error(err);
});
}
});
for
循环在这里仅执行一次。如果我尝试删除return
并仅保留图像,那么它会正确地创建5个作物,但会给我一个错误:UnhandledPromiseRejectionWarning
。
谢谢您的帮助!
答案 0 :(得分:0)
如上所述,您的for
循环及其内部的回调将在您执行return
语句后退出。因此,如果您希望for
循环继续运行,则必须删除return
语句。
通过将代码更改为以下代码,您可以对图像的写入进行排序,并确保记录了此特定代码中的任何错误,并且在此代码中没有未处理的拒绝:
bot.on('message', function(message, channelID, userID, user, evt) {
if (message.content.toString().includes(bot.user.toString())) {
message.channel.send("Use / instead")
}
if (message.content.toString() == "/ping") {
message.channel.send("pong")
}
if (message.attachments && message.content.toString().includes("/split")) {
Jimp.read(message.attachments.array()[0].url).then(async (image) => {
for (let i = 0; i < 5; i++) {
try {
await image.clone()
.crop(0, image.bitmap.height / 5 * i, image.bitmap.width, image.bitmap.height / 5)
.writeAsync('./files/cropped' + i + '.png');
console.log(`image #${i} written`);
} catch(e) {
console.error(`Error writing image #${i}`, e);
}
}
}).catch(err => {
console.error(err);
});
}
});