|
| 1 | +import { PNG } from 'pngjs'; |
| 2 | +import { CanvasService } from './canvas.service.js'; |
| 3 | + |
| 4 | +export class ImageService { |
| 5 | + static async generateLobbyPng(lobbyName: string, scale: number = 1): Promise<PNG> { |
| 6 | + const { width, height, palette, data } = await CanvasService.getState(lobbyName); |
| 7 | + |
| 8 | + // Validate scale to prevent memory issues |
| 9 | + const validScale = Math.max(1, Math.min(Math.floor(scale), 10)); // Clamp between 1 and 10 |
| 10 | + const scaledWidth = width * validScale; |
| 11 | + const scaledHeight = height * validScale; |
| 12 | + |
| 13 | + const png = new PNG({ width: scaledWidth, height: scaledHeight }); |
| 14 | + |
| 15 | + // Pre-calculate RGB values from hex palette |
| 16 | + const rgbPalette = palette.map(hex => { |
| 17 | + const r = parseInt(hex.slice(1, 3), 16); |
| 18 | + const g = parseInt(hex.slice(3, 5), 16); |
| 19 | + const b = parseInt(hex.slice(5, 7), 16); |
| 20 | + return [r, g, b]; |
| 21 | + }); |
| 22 | + |
| 23 | + // Populate PNG buffer with Nearest-Neighbor Scaling |
| 24 | + for (let y = 0; y < scaledHeight; y++) { |
| 25 | + const srcY = Math.floor(y / validScale); |
| 26 | + for (let x = 0; x < scaledWidth; x++) { |
| 27 | + const srcX = Math.floor(x / validScale); |
| 28 | + |
| 29 | + const colorIdx = data[srcY * width + srcX]; |
| 30 | + const [r, g, b] = rgbPalette[colorIdx] || [0, 0, 0]; |
| 31 | + |
| 32 | + const pngIdx = (y * scaledWidth + x) << 2; |
| 33 | + png.data[pngIdx] = r; |
| 34 | + png.data[pngIdx + 1] = g; |
| 35 | + png.data[pngIdx + 2] = b; |
| 36 | + png.data[pngIdx + 3] = 255; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return png; |
| 41 | + } |
| 42 | +} |
0 commit comments