( context: ImageCompressionContext, sharp: SharpFunction, )
| 659 | } |
| 660 | |
| 661 | async function tryProgressiveResizing( |
| 662 | context: ImageCompressionContext, |
| 663 | sharp: SharpFunction, |
| 664 | ): Promise<CompressedImageResult | null> { |
| 665 | const scalingFactors = [1.0, 0.75, 0.5, 0.25] |
| 666 | |
| 667 | for (const scalingFactor of scalingFactors) { |
| 668 | const newWidth = Math.round( |
| 669 | (context.metadata.width || 2000) * scalingFactor, |
| 670 | ) |
| 671 | const newHeight = Math.round( |
| 672 | (context.metadata.height || 2000) * scalingFactor, |
| 673 | ) |
| 674 | |
| 675 | let resizedImage = sharp(context.imageBuffer).resize(newWidth, newHeight, { |
| 676 | fit: 'inside', |
| 677 | withoutEnlargement: true, |
| 678 | }) |
| 679 | |
| 680 | // Apply format-specific optimizations |
| 681 | resizedImage = applyFormatOptimizations(resizedImage, context.format) |
| 682 | |
| 683 | const resizedBuffer = await resizedImage.toBuffer() |
| 684 | |
| 685 | if (resizedBuffer.length <= context.maxBytes) { |
| 686 | return createCompressedImageResult( |
| 687 | resizedBuffer, |
| 688 | context.format, |
| 689 | context.originalSize, |
| 690 | ) |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | return null |
| 695 | } |
| 696 | |
| 697 | function applyFormatOptimizations( |
| 698 | image: SharpInstance, |
no test coverage detected