简体   繁体   中英

How do I merge images in discord.js for a discord bot?

I'm trying to make a command that merges the avatar with an image eg jail bars on the avatar if someone types =jail for example - I have already made a command handler that sorts the command. I can't work out, however, how to achieve this. I am using a windows platform (apparently this means I cannot use node gd)

You can use Jimp for that. Here's the NPM site: https://www.npmjs.com/package/jimp

It allows you to modify pictures, add text, etc. What you would want would look similar to this:

//an array of all images we're using. MAKE SURE THEIR SIZES MATCH
var images = [<link to the user's avatar>, <link to an image of jail bars>]
var jimps = []
//turns the images into readable variables for jimp, then pushes them into a new array
for (var i = 0; i < images.length; i++){
    jimps.push(jimp.read(images[i]))
}
//creates a promise to handle the jimps
await Promise.all(jimps).then(function(data) {
    return Promise.all(jimps)
}).then(async function(data){
    // --- THIS IS WHERE YOU MODIFY THE IMAGES --- \\
    data[0].composite(data[1], 0, 0) //adds the second specified image (the jail bars) on top of the first specified image (the avatar). "0, 0" define where the second image is placed, originating from the top left corner
    //you CAN resize the second image to fit the first one like this, if necessary. The "100, 100" is the new size in pixels.
    //data[1].resize(100,100)

    //this saves our modified image
    data[0].write(<path on your local disk to save the image in>)
})

Now all you have to do is send the image from your local disk:

message.channel.send(`Jailed!`, {file: `${<path to the image>}`})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM