const fs = require("fs"); const path = require("path"); const LibRaw = require("../lib/index"); /** * Multi-Size JPEG Generation Test Suite * Tests the capability to generate multiple JPEG files of different sizes from a single RAW file */ class MultiSizeJPEGTests { constructor() { this.testFiles = []; this.outputDir = path.join(__dirname, "output", "multi-size-jpeg"); this.results = { generation: { tested: 0, passed: 0, successRate: 0, generationResults: [], }, performance: { averageTime: 0, totalFiles: 0, sizeGenerationTimes: [] }, quality: { compressionAnalysis: [], sizeRangeAnalysis: [] }, }; // Ensure output directory exists if (!fs.existsSync(this.outputDir)) { fs.mkdirSync(this.outputDir, { recursive: true }); } } log(message, type = "info") { const symbols = { success: "✅", error: "❌", warning: "⚠️", info: "ℹ️", test: "🧪", data: "📊", }; console.log(`${symbols[type] || symbols.info} ${message}`); } findTestFiles() { const sampleDir = path.join(__dirname, "..", "sample-images"); if (!fs.existsSync(sampleDir)) { return []; } const rawExtensions = [ ".cr2", ".cr3", ".nef", ".arw", ".dng", ".raf", ".rw2", ]; const files = fs .readdirSync(sampleDir) .filter((file) => rawExtensions.includes(path.extname(file).toLowerCase()) ) .map((file) => path.join(sampleDir, file)); return files; } async testMultiSizeJPEGGeneration() { console.log("\n📐 Multi-Size JPEG Generation from RAW Files"); console.log("============================================"); this.testFiles = this.findTestFiles(); if (this.testFiles.length === 0) { this.log("No RAW test files found in sample-images directory", "error"); return false; } this.log(`Found ${this.testFiles.length} RAW test files`, "success"); // Define comprehensive size configurations const sizeConfigs = [ // Thumbnail sizes { name: "thumbnail_small", width: 150, height: 100, quality: 85, category: "thumbnail", description: "Tiny thumbnail for lists", }, { name: "thumbnail_medium", width: 300, height: 200, quality: 85, category: "thumbnail", description: "Standard thumbnail", }, // Web preview sizes { name: "web_small", width: 480, height: 320, quality: 80, category: "web", description: "Mobile web preview", }, { name: "web_medium", width: 800, height: 600, quality: 85, category: "web", description: "Tablet web preview", }, { name: "web_large", width: 1200, height: 800, quality: 85, category: "web", description: "Desktop web preview", }, // High-definition sizes { name: "hd_720p", width: 1280, height: 720, quality: 85, category: "hd", description: "HD 720p format", }, { name: "hd_1080p", width: 1920, height: 1080, quality: 85, category: "hd", description: "Full HD 1080p", }, { name: "hd_1440p", width: 2560, height: 1440, quality: 85, category: "hd", description: "QHD 1440p", }, // Ultra-high definition { name: "uhd_4k", width: 3840, height: 2160, quality: 80, category: "uhd", description: "4K UHD format", }, // Quality variants (full size) { name: "full_standard", quality: 85, category: "full", description: "Full size, standard quality", }, { name: "full_high", quality: 95, category: "full", description: "Full size, high quality", }, { name: "full_maximum", quality: 100, category: "full", description: "Full size, maximum quality", }, ]; let totalTests = 0; let passedTests = 0; const generationResults = []; // Test with first 3 files for comprehensive analysis for (const testFile of this.testFiles.slice(0, 3)) { const processor = new LibRaw(); try { totalTests++; const fileName = path.basename(testFile, path.extname(testFile)); this.log(`\nProcessing: ${fileName}`, "test"); const overallStartTime = Date.now(); await processor.loadFile(testFile); // Get original image metadata const metadata = await processor.getMetadata(); const megapixels = ( (metadata.width * metadata.height) / 1000000 ).toFixed(1); this.log( ` Original: ${metadata.width}x${metadata.height} (${megapixels}MP)`, "data" ); const sizeResults = []; let successfulSizes = 0; const categoryTimes = {}; // Create subdirectory for this file const fileOutputDir = path.join(this.outputDir, fileName); if (!fs.existsSync(fileOutputDir)) { fs.mkdirSync(fileOutputDir, { recursive: true }); } for (const config of sizeConfigs) { try { const outputPath = path.join( fileOutputDir, `${fileName}_${config.name}.jpg` ); const sizeStartTime = Date.now(); // Prepare conversion options const conversionOptions = { quality: config.quality, fastMode: true, effort: 3, }; // Add size constraints if specified if (config.width && config.height) { conversionOptions.width = config.width; conversionOptions.height = config.height; } const result = await processor.convertToJPEG( outputPath, conversionOptions ); const sizeTime = Date.now() - sizeStartTime; if (fs.existsSync(outputPath)) { const stats = fs.statSync(outputPath); const outputDimensions = result.metadata.outputDimensions; // Calculate efficiency metrics const originalPixels = metadata.width * metadata.height; const outputPixels = outputDimensions.width * outputDimensions.height; const pixelReduction = ( ((originalPixels - outputPixels) / originalPixels) * 100 ).toFixed(1); sizeResults.push({ name: config.name, category: config.category, description: config.description, targetSize: config.width && config.height ? `${config.width}x${config.height}` : "Original", actualSize: `${outputDimensions.width}x${outputDimensions.height}`, fileSize: stats.size, fileSizeKB: (stats.size / 1024).toFixed(1), fileSizeMB: (stats.size / 1024 / 1024).toFixed(2), quality: config.quality, processingTime: sizeTime, compressionRatio: result.metadata.fileSize.compressionRatio, pixelReduction: config.width ? pixelReduction : 0, aspectRatio: ( outputDimensions.width / outputDimensions.height ).toFixed(2), success: true, }); // Track category timing if (!categoryTimes[config.category]) categoryTimes[config.category] = []; categoryTimes[config.category].push(sizeTime); this.log( ` ✓ ${config.name}: ${outputDimensions.width}x${ outputDimensions.height }, ${(stats.size / 1024).toFixed(1)}KB (${sizeTime}ms)`, "success" ); successfulSizes++; } else { sizeResults.push({ name: config.name, category: config.category, success: false, error: "File not created", }); this.log(` ✗ ${config.name}: File not created`, "error"); } } catch (sizeError) { sizeResults.push({ name: config.name, category: config.category, success: false, error: sizeError.message, }); this.log(` ✗ ${config.name}: ${sizeError.message}`, "error"); } } const totalTime = Date.now() - overallStartTime; generationResults.push({ file: fileName, originalDimensions: `${metadata.width}x${metadata.height}`, originalMegapixels: megapixels, totalProcessingTime: totalTime, successfulSizes: successfulSizes, totalSizes: sizeConfigs.length, categoryTimes: categoryTimes, sizeResults: sizeResults, }); if (successfulSizes > 0) { passedTests++; this.log( ` ✓ Generated ${successfulSizes}/${sizeConfigs.length} sizes in ${totalTime}ms`, "success" ); // Generate comprehensive analysis report await this.generateComprehensiveReport( fileName, sizeResults, fileOutputDir, metadata ); } else { this.log(` ✗ Failed to generate any sizes`, "error"); } await processor.close(); } catch (error) { this.log(` ✗ Multi-size generation failed: ${error.message}`, "error"); try { await processor.close(); } catch (e) {} } } // Store results this.results.generation = { tested: totalTests, passed: passedTests, successRate: totalTests > 0 ? ((passedTests / totalTests) * 100).toFixed(1) : 0, generationResults: generationResults, }; // Analyze results this.analyzePerformance(generationResults); this.analyzeQualityAndCompression(generationResults); // Print comprehensive results this.printDetailedResults(generationResults); this.log( `\nMulti-size JPEG generation completed: ${passedTests}/${totalTests} files processed successfully (${this.results.generation.successRate}%)`, passedTests > 0 ? "success" : "warning" ); return passedTests > 0; } analyzePerformance(generationResults) { const allTimes = []; const categoryPerformance = {}; generationResults.forEach((result) => { allTimes.push(result.totalProcessingTime); Object.entries(result.categoryTimes).forEach(([category, times]) => { if (!categoryPerformance[category]) categoryPerformance[category] = []; categoryPerformance[category].push(...times); }); }); this.results.performance = { averageTime: allTimes.length > 0 ? (allTimes.reduce((a, b) => a + b, 0) / allTimes.length).toFixed(0) : 0, totalFiles: generationResults.length, categoryPerformance: Object.fromEntries( Object.entries(categoryPerformance).map(([category, times]) => [ category, { average: (times.reduce((a, b) => a + b, 0) / times.length).toFixed( 0 ), min: Math.min(...times), max: Math.max(...times), count: times.length, }, ]) ), }; } analyzeQualityAndCompression(generationResults) { const compressionAnalysis = []; const sizeRangeAnalysis = []; generationResults.forEach((result) => { const successful = result.sizeResults.filter((r) => r.success); if (successful.length >= 2) { const sizes = successful.sort((a, b) => a.fileSize - b.fileSize); const smallest = sizes[0]; const largest = sizes[sizes.length - 1]; compressionAnalysis.push({ file: result.file, smallestSize: smallest.fileSizeKB, largestSize: largest.fileSizeKB, compressionRange: (largest.fileSize / smallest.fileSize).toFixed(1), sizeCount: successful.length, }); // Analyze by category const categoryStats = {}; successful.forEach((size) => { if (!categoryStats[size.category]) categoryStats[size.category] = []; categoryStats[size.category].push(parseFloat(size.fileSizeKB)); }); sizeRangeAnalysis.push({ file: result.file, categoryStats: Object.fromEntries( Object.entries(categoryStats).map(([category, sizes]) => [ category, { average: ( sizes.reduce((a, b) => a + b, 0) / sizes.length ).toFixed(1), min: Math.min(...sizes).toFixed(1), max: Math.max(...sizes).toFixed(1), count: sizes.length, }, ]) ), }); } }); this.results.quality = { compressionAnalysis, sizeRangeAnalysis }; } async generateComprehensiveReport( fileName, sizeResults, outputDir, metadata ) { try { const reportPath = path.join(outputDir, `${fileName}_analysis.html`); const successful = sizeResults.filter((r) => r.success); const failed = sizeResults.filter((r) => !r.success); // Group by category const categories = {}; successful.forEach((result) => { if (!categories[result.category]) categories[result.category] = []; categories[result.category].push(result); }); const htmlContent = `
| Size Name | Category | Target | Actual | File Size | Quality | Processing | Compression | Status |
|---|---|---|---|---|---|---|---|---|
| ${result.name || "N/A"} | ${result.category || "N/A"} | ${result.targetSize || "N/A"} | ${result.actualSize || "N/A"} | ${ result.fileSizeKB || "N/A" }KB | ${result.quality || "N/A"}% | ${result.processingTime || "N/A"}ms | ${result.compressionRatio || "N/A"} | ${ result.success ? "✓ Success" : "✗ " + (result.error || "Failed") } |