javascriptnode.jsdiscord.jsimage-manipulationjimp

discord.js putting an image on another image


I've been trying to make a command that when you send an image or a url of an image it puts that image on another image that I already have in the code and I keep getting errors every time I try changing it to either imageTemp (which is the image you put your image on) or image`` or messageAttachment```. I'll put my code below so you could see what the problem is.

const { MessageAttachment } = require('discord.js');
const Jimp = require('jimp');
const discord = require('discord.js')

module.exports = {
  name: "img",
  aliases: [],
  run: async (client, message, args) => {
    let messageAttachment = message.attachments.size > 0 ? message.attachments.array()[0].url : null
    try {
      let imageTemp = "https://upload.wikimedia.org/wikipedia/commons/8/8a/Banana-Single.jpg"
      let image = await Jimp.read(messageAttachment);
      let buffer = await image.getBufferAsync(Jimp.MIME_JPEG);

    Jimp.read(imageTemp).then(image => {
    image.composite(messageAttachment, 10, 10)
    })

      message.channel.send(new MessageAttachment(buffer));
    } catch (err) {
      console.log(err);
      message.channel.send('Oops, there was an error. Try inputting the command again.');
    }
  },
};

And here's the result and the errors I get https://i.sstatic.net/vnTkn.jpg

result


Solution

  • The Jimp.composite() method accepts a Jimp image object as its first argument. Not an url (messageAttachment) as you are passing in. Also you are saving the image to buffer before you modify it.

    And the error you mentioned occurs when messageAttachment is null. You should check and return if the message has no attachments.

    const imageTemp = "https://upload.wikimedia.org/wikipedia/commons/8/8a/Banana-Single.jpg";
    const messageAttachment = message.attachments.size > 0 ? message.attachments.array()[0].url : null;
    
    // Exit if there is no message attachment present in the message
    if (!messageAttachment) return;
    
    // Resolve the temporary image url to Jimp object
    const firstImage = await Jimp.read(imageTemp);
    // Resolve the message attachment image url to Jimp object
    const secondImage = await Jimp.read(messageAttachment);
    
    // Composite the two images together (modifies the firstImage object)
    firstImage.composite(secondImage, 10, 10);
    
    // Save the resulting image to buffer
    const buffer = await firstImage.getBufferAsync(Jimp.MIME_JPEG);
    
    // Send the buffer as a message attachment
    message.channel.send("Combined image:", {files: [{ attachment: buffer }]});
    

    enter image description here