Crop pokemon box image to content

This commit is contained in:
Dragon Fire
2024-03-29 16:47:45 -04:00
parent ea6a3f0788
commit 3e06f1e42c
3 changed files with 38 additions and 1 deletions
+11 -1
View File
@@ -1,4 +1,6 @@
const Command = require('../../framework/Command');
const { createCanvas } = require('canvas');
const { cropToContent } = require('../../util/Canvas');
module.exports = class PokedexBoxSpriteCommand extends Command {
constructor(client) {
@@ -65,9 +67,17 @@ module.exports = class PokedexBoxSpriteCommand extends Command {
async run(msg, { pokemon }) {
try {
if (!this.client.pokemon.sprites) await this.client.pokemon.loadSprites();
const canvas = createCanvas(250, 250);
const ctx = canvas.getContext('2d');
const x = 40 * (this.id % 12);
const y = Math.floor(this.id / 12) * 30;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(this.store.sprites, x, y, 40, 30, 0, 0, 250, 250);
cropToContent(ctx, canvas.width, canvas.height);
return msg.say(`#${pokemon.displayID} - ${pokemon.name}`, {
files: [{
attachment: await pokemon.generateBoxImage(),
attachment: canvas.toBuffer(),
name: 'box.png'
}]
});
+2
View File
@@ -2,6 +2,7 @@ const request = require('node-superfetch');
const { createCanvas } = require('canvas');
const path = require('path');
const { removeDuplicates, firstUpperCase, delay } = require('../../util/Util');
const { cropToContent } = require('../../util/Canvas');
const missingno = require('../../assets/json/missingno');
const versions = require('../../assets/json/pokedex-location');
@@ -157,6 +158,7 @@ module.exports = class Pokemon {
const x = 40 * (this.id % 12);
const y = Math.floor(this.id / 12) * 30;
ctx.drawImage(this.store.sprites, x, y, 40, 30, 0, 0, 40, 30);
cropToContent(ctx, canvas.width, canvas.height);
return canvas.toBuffer();
}
+25
View File
@@ -146,6 +146,31 @@ module.exports = class CanvasUtil {
return ctx;
}
static cropToContent(ctx, w, h) {
const pix = { x: [], y: [] };
const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
let index;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
index = ((y * w) + x) * 4;
if (imageData.data[index + 3] > 0) {
pix.x.push(x);
pix.y.push(y);
}
}
}
pix.x.sort((a, b) => a - b);
pix.y.sort((a, b) => a - b);
const n = pix.x.length - 1;
const newW = (1 + pix.x[n]) - pix.x[0];
const newH = (1 + pix.y[n]) - pix.y[0];
const cut = ctx.getImageData(pix.x[0], pix.y[0], newW, newH);
ctx.canvas.width = newW;
ctx.canvas.height = newH;
ctx.putImageData(cut, 0, 0);
return ctx;
}
static hasAlpha(image) {
const canvas = createCanvas(image.width, image.height);
const ctx = canvas.getContext('2d');