( context: ImageCompressionContext, sharp: SharpFunction, )
| 644 | } |
| 645 | |
| 646 | async function tryProgressiveResizing( |
| 647 | context: ImageCompressionContext, |
| 648 | sharp: SharpFunction, |
| 649 | ): Promise<CompressedImageResult | null> { |
| 650 | const scalingFactors = [1.0, 0.75, 0.5, 0.25] |
| 651 | |
| 652 | for (const scalingFactor of scalingFactors) { |
| 653 | const newWidth = Math.round( |
| 654 | (context.metadata.width || 2000) * scalingFactor, |
| 655 | ) |
| 656 | const newHeight = Math.round( |
| 657 | (context.metadata.height || 2000) * scalingFactor, |
| 658 | ) |
| 659 | |
| 660 | let resizedImage = sharp(context.imageBuffer).resize(newWidth, newHeight, { |
| 661 | fit: 'inside', |
| 662 | withoutEnlargement: true, |
| 663 | }) |
| 664 | |
| 665 | // Apply format-specific optimizations |
| 666 | resizedImage = applyFormatOptimizations(resizedImage, context.format) |
| 667 | |
| 668 | const resizedBuffer = await resizedImage.toBuffer() |
| 669 | |
| 670 | if (resizedBuffer.length <= context.maxBytes) { |
| 671 | return createCompressedImageResult( |
| 672 | resizedBuffer, |
| 673 | context.format, |
| 674 | context.originalSize, |
| 675 | ) |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | return null |
| 680 | } |
| 681 | |
| 682 | function applyFormatOptimizations( |
| 683 | image: SharpInstance, |
no test coverage detected