UNPKG

kiutils

Version:

🎑 (Library) an Javascript library that provide various utilities, including Image manipulation tools, Discord-related utilities, and a logger.

286 lines • 11.1 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createThumbnail = exports.convertImageFile = exports.convertImage = exports.ImageFormat = void 0; const path = __importStar(require("path")); const sharp_1 = __importDefault(require("sharp")); /** * Supported image formats for conversion */ var ImageFormat; (function (ImageFormat) { ImageFormat["PNG"] = "png"; ImageFormat["JPEG"] = "jpeg"; ImageFormat["JPG"] = "jpeg"; ImageFormat["WEBP"] = "webp"; ImageFormat["AVIF"] = "avif"; ImageFormat["TIFF"] = "tiff"; ImageFormat["GIF"] = "gif"; ImageFormat["HEIF"] = "heif"; })(ImageFormat || (exports.ImageFormat = ImageFormat = {})); /** * Converts an image from one format to another using Sharp * @param {string|Buffer} input - Path to the source image or image buffer * @param {ImageFormat} format - Target format to convert to * @param {ConversionOptions} options - Additional conversion options * @returns {Promise<Buffer>} Converted image as buffer * @example * const { convertImage, ImageFormat } = require("kiutils"); * * // Convert from file path * convertImage("image.png", ImageFormat.WEBP) * .then(buffer => fs.writeFileSync("image.webp", buffer)); * * // Convert from buffer with options * const inputBuffer = fs.readFileSync("image.jpg"); * convertImage(inputBuffer, ImageFormat.PNG, { width: 800 }) * .then(buffer => fs.writeFileSync("resized.png", buffer)); */ async function convertImage(input, format, options = {}) { try { // Initialize Sharp with the input let imageProcessor = typeof input === "string" ? (0, sharp_1.default)(input) : (0, sharp_1.default)(input); // Apply resizing if width or height is specified if (options.width || options.height) { imageProcessor = imageProcessor.resize({ width: options.width, height: options.height, fit: options.fit || "contain", withoutEnlargement: true }); } // Preserve metadata if requested if (options.withMetadata) { imageProcessor = imageProcessor.withMetadata(); } // Apply format-specific options switch (format) { case ImageFormat.PNG: imageProcessor = imageProcessor.png({ compressionLevel: 9, adaptiveFiltering: true, progressive: true }); break; case ImageFormat.JPEG: case ImageFormat.JPG: imageProcessor = imageProcessor.jpeg({ quality: options.quality || 80, progressive: true, optimizeCoding: true }); break; case ImageFormat.WEBP: imageProcessor = imageProcessor.webp({ quality: options.quality || 80, lossless: options.quality === 100, nearLossless: options.quality === 100 }); break; case ImageFormat.AVIF: imageProcessor = imageProcessor.avif({ quality: options.quality || 60, lossless: options.quality === 100 }); break; case ImageFormat.TIFF: imageProcessor = imageProcessor.tiff({ quality: options.quality || 80, compression: 'lzw' }); break; case ImageFormat.GIF: imageProcessor = imageProcessor.gif(); break; case ImageFormat.HEIF: imageProcessor = imageProcessor.heif({ quality: options.quality || 80 }); break; default: throw new Error(`Unsupported output format: ${format}`); } // Process and return the image buffer return await imageProcessor.toBuffer(); } catch (error) { throw new Error(`Failed to convert image: ${error instanceof Error ? error.message : String(error)}`); } } exports.convertImage = convertImage; /** * Converts an image file from one format to another and saves to a file * @param {string} inputPath - Path to the source image * @param {string} outputPath - Path where the converted image will be saved * @param {ConversionOptions} options - Additional conversion options * @returns {Promise<string>} Path to the converted image * @example * const { convertImageFile, ImageFormat } = require("kiutils"); * * // Convert PNG to JPEG * convertImageFile("image.png", "converted.jpg", { quality: 90 }) * .then(outputPath => console.log(`Converted image saved to ${outputPath}`)); */ async function convertImageFile(inputPath, outputPath, options = {}) { if (!inputPath) throw new Error("The parameter 'inputPath' is missing"); if (!outputPath) throw new Error("The parameter 'outputPath' is missing"); try { // Determine format from output file extension const extension = path.extname(outputPath).toLowerCase().slice(1); const format = extension; if (!Object.values(ImageFormat).includes(format)) { throw new Error(`Unsupported output format: ${extension}`); } // For file-to-file conversion, we can use Sharp's built-in toFile method // which is more efficient than writing buffer to file const imageProcessor = (0, sharp_1.default)(inputPath); // Apply resizing if width or height is specified if (options.width || options.height) { imageProcessor.resize({ width: options.width, height: options.height, fit: options.fit || "contain", withoutEnlargement: true }); } // Preserve metadata if requested if (options.withMetadata) { imageProcessor.withMetadata(); } // Apply format-specific options switch (format) { case ImageFormat.PNG: imageProcessor.png({ compressionLevel: 9, adaptiveFiltering: true, progressive: true }); break; case ImageFormat.JPEG: case ImageFormat.JPG: imageProcessor.jpeg({ quality: options.quality || 80, progressive: true, optimizeCoding: true }); break; case ImageFormat.WEBP: imageProcessor.webp({ quality: options.quality || 80, lossless: options.quality === 100, nearLossless: options.quality === 100 }); break; case ImageFormat.AVIF: imageProcessor.avif({ quality: options.quality || 60, lossless: options.quality === 100 }); break; case ImageFormat.TIFF: imageProcessor.tiff({ quality: options.quality || 80, compression: 'lzw' }); break; case ImageFormat.GIF: imageProcessor.gif(); break; case ImageFormat.HEIF: imageProcessor.heif({ quality: options.quality || 80 }); break; } // Save to file await imageProcessor.toFile(outputPath); return outputPath; } catch (error) { throw new Error(`Failed to convert image file: ${error instanceof Error ? error.message : String(error)}`); } } exports.convertImageFile = convertImageFile; /** * Creates image thumbnails quickly and efficiently * @param {string|Buffer} input - Path to the source image or image buffer * @param {number} width - Thumbnail width * @param {number} height - Thumbnail height (optional, will maintain aspect ratio if omitted) * @param {ImageFormat} format - Output format (default: png) * @returns {Promise<Buffer>} Thumbnail image as buffer * @example * const { createThumbnail, ImageFormat } = require("kiutils"); * * createThumbnail("large-image.jpg", 200) * .then(buffer => fs.writeFileSync("thumbnail.png", buffer)); */ async function createThumbnail(input, width, height, format = ImageFormat.PNG) { if (!input) throw new Error("The parameter 'input' is missing"); if (!width) throw new Error("The parameter 'width' is missing"); try { // Initialize Sharp with the input const imageProcessor = typeof input === "string" ? (0, sharp_1.default)(input) : (0, sharp_1.default)(input); // Create the thumbnail imageProcessor.resize({ width, height, fit: "inside", withoutEnlargement: true }); // Set output format switch (format) { case ImageFormat.PNG: imageProcessor.png({ compressionLevel: 9 }); break; case ImageFormat.JPEG: case ImageFormat.JPG: imageProcessor.jpeg({ quality: 80 }); break; case ImageFormat.WEBP: imageProcessor.webp({ quality: 80 }); break; default: imageProcessor.toFormat(format); } // Return the thumbnail buffer return await imageProcessor.toBuffer(); } catch (error) { throw new Error(`Failed to create thumbnail: ${error instanceof Error ? error.message : String(error)}`); } } exports.createThumbnail = createThumbnail; //# sourceMappingURL=imageConverter.js.map