Короче говоря, я создаю бота Discord в качестве учебного проекта и просто пытаюсь использовать Pixelit, API для пикселизации изображений, а затем отправить их обратно на сервер Discord. У меня нет проблем с отправкой изображений обратно (спасибо @Remy Kabel!), но проблема в самой пикселизации.
Когда я отправляю изображение, происходит одно из двух, в зависимости от размеров изображения. Если его высота превышает ширину, преобразование просто завершится неудачей, и появится сообщение «Упс! Мне не удалось пикселизировать это изображение». ошибка в Discord и выдача этой ошибки на терминал VS Code:
Код: Выделить всё
Error pixelating image: TypeError: Cannot set properties of undefined (setting '0')
at getData (C:\Users\KJH04\Desktop\discordbot\node_modules\pixelit\src\sampling.js:26:26)
at sampling (C:\Users\KJH04\Desktop\discordbot\node_modules\pixelit\src\sampling.js:47:12)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async pixelIt (C:\Users\KJH04\Desktop\discordbot\node_modules\pixelit\src\index.js:16:21)
at async pixelateAndSend (file:///C:/Users/KJH04/Desktop/discordbot/index.js:74:3)
at async Client. (file:///C:/Users/KJH04/Desktop/discordbot/index.js:47:7)

Вот весь исходный код:
Код: Выделить всё
import dotenv from 'dotenv';
dotenv.config();
import { Client, GatewayIntentBits } from 'discord.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import sharp from 'sharp';
import {imageSizeFromFile} from 'image-size/fromFile';
// pixelit supports both ESM and CJS
import * as pixelitModule from 'pixelit';
const pixelit = pixelitModule.default || pixelitModule;
// Some path setup helpers
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Initialize Discord client with correct intents
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
// Log in confirmation
client.once('clientReady', () => {
console.log(`✅ Logged in as ${client.user.tag}`);
});
// Listen for messages
client.on('messageCreate', async message => {
console.log("Found message!");
// Ignore bot messages
if (message.author.bot) return;
// Check for image attachments
if (message.attachments.size > 0) {
const attachment = message.attachments.find(a => a.contentType?.startsWith('image/'));
if (!attachment) return;
console.log(`Received image from ${message.author.username}`);
try {
await pixelateAndSend(attachment.url, message);
} catch (err) {
console.error('Error pixelating image:', err);
await message.reply('Oops! I couldn’t pixelate that image.');
}
}
});
// Pixelate function using native fetch
async function pixelateAndSend(imgUrl, message) {
// Fetch image as buffer
const response = await fetch(imgUrl);
if (!response.ok) throw new Error(`Failed to fetch image: ${response.status} ${response.statusText}`);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
// Save the image temporarily to disk
const inputPath = path.join(__dirname, `input_${Date.now()}`+imgUrl.substring(imgUrl.lastIndexOf('.'),imgUrl.lastIndexOf('.')+4));
const outputPath = path.join(__dirname, `pixelated_${Date.now()}.svg`);
fs.writeFileSync(inputPath, buffer);
// Get size of image and initialize pixel size
var test = await imageSizeFromFile(inputPath);
var pixelSize = 20;
// Run pixelit to create SVG file --- Math.floor(test.height/pixelSize)
await pixelit(inputPath, { pixel: pixelSize, x: Math.floor(test.width/pixelSize), y: Math.floor(test.height/pixelSize)}, { path: outputPath });
// Convert SVG to PNG
await sharp(outputPath).png().toFile('output.png');
// Send the result to Discord
await message.channel.send({ files: ['output.png'] });
// Clean up
try{
fs.unlinkSync(inputPath);
fs.unlinkSync(outputPath);
fs.unlinkSync('output.png');
} catch(err){console.error('Error deleting file: ', err)}
}
// Start the bot
client.login(process.env.DISCORD_TOKEN);
- Выяснить, как редактировать текущий код (думал, что я смогу использовать resizeImage(), но не смог заставить это работать в текущей конфигурации)
- Найти другой способ использования Pixelit
- Просто скажите мне использовать другой API для пикселизации (в идеале, чтобы мне не пришлось подписывать готов или что-то в этом роде, поэтому я в первую очередь использовал Pixelit)
Всякая помощь приветствуется!
Подробнее здесь: https://stackoverflow.com/questions/798 ... rrect-size
Мобильная версия