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