|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const Jimp = require("jimp"); |
| 4 | +const fs = require("fs"); |
| 5 | +const path = require("path"); // Import the 'path' module for working with file paths |
| 6 | + |
| 7 | +const outputFolder = "output"; |
| 8 | + |
| 9 | +function sliceImage(filename, width, height) { |
| 10 | + Jimp.read(filename, (err, image) => { |
| 11 | + if (err) { |
| 12 | + // Try again by appending '.png' to the filename |
| 13 | + const pngFilename = `${filename}.png`; |
| 14 | + Jimp.read(pngFilename, (pngErr, pngImage) => { |
| 15 | + if (pngErr) { |
| 16 | + console.error("Error reading the image:", pngErr); |
| 17 | + return; |
| 18 | + } |
| 19 | + continueSlicing(pngImage, width, height, filename); |
| 20 | + }); |
| 21 | + } else { |
| 22 | + continueSlicing(image, width, height, filename); |
| 23 | + } |
| 24 | + }); |
| 25 | +} |
| 26 | + |
| 27 | +function continueSlicing(image, width, height, inputFilename) { |
| 28 | + // If height is not specified, use width as height |
| 29 | + height = height || width; |
| 30 | + |
| 31 | + const imageWidth = image.getWidth(); |
| 32 | + const imageHeight = image.getHeight(); |
| 33 | + |
| 34 | + // Calculate the number of slices in both dimensions |
| 35 | + const horizontalSlices = Math.ceil(imageWidth / width); |
| 36 | + const verticalSlices = Math.ceil(imageHeight / height); |
| 37 | + |
| 38 | + // Create a folder for output if it doesn't exist |
| 39 | + if (!fs.existsSync(outputFolder)) { |
| 40 | + fs.mkdirSync(outputFolder); |
| 41 | + } |
| 42 | + |
| 43 | + // Slice the image and save each segment |
| 44 | + for (let y = 0; y < verticalSlices; y++) { |
| 45 | + for (let x = 0; x < horizontalSlices; x++) { |
| 46 | + const startX = x * width; |
| 47 | + const startY = y * height; |
| 48 | + |
| 49 | + const sliceWidth = Math.min(width, imageWidth - startX); |
| 50 | + const sliceHeight = Math.min(height, imageHeight - startY); |
| 51 | + |
| 52 | + const slice = image.clone().crop(startX, startY, sliceWidth, sliceHeight); |
| 53 | + |
| 54 | + // Incorporate the input filename into the output filename |
| 55 | + const baseFilename = path.basename( |
| 56 | + inputFilename, |
| 57 | + path.extname(inputFilename), |
| 58 | + ); |
| 59 | + const outputFilename = `${outputFolder}/${baseFilename}_${x}_${y}.png`; |
| 60 | + |
| 61 | + slice.write(outputFilename); |
| 62 | + console.log(`Slice saved: ${outputFilename}`); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +// Get input from the command line arguments |
| 68 | +const [filename, width, height] = process.argv.slice(2); |
| 69 | + |
| 70 | +if (!filename || !width) { |
| 71 | + console.log("Usage: node sliceImage.js <filename> <width> [height]"); |
| 72 | +} else { |
| 73 | + sliceImage(filename, parseInt(width), parseInt(height)); |
| 74 | +} |
0 commit comments