* Attempts to compress an image to fit within the max base64 size. * Tries different dimension/quality combinations until one fits.
(fileBuffer: Buffer)
| 113 | * Tries different dimension/quality combinations until one fits. |
| 114 | */ |
| 115 | async function compressImageToFitSize(fileBuffer: Buffer): Promise<CompressionResult> { |
| 116 | const image = await Jimp.read(fileBuffer) |
| 117 | const originalWidth = image.bitmap.width |
| 118 | const originalHeight = image.bitmap.height |
| 119 | |
| 120 | let bestBase64Size = Infinity |
| 121 | let attemptCount = 0 |
| 122 | |
| 123 | for (const maxDimension of DIMENSION_LIMITS) { |
| 124 | for (const quality of COMPRESSION_QUALITIES) { |
| 125 | attemptCount++ |
| 126 | |
| 127 | const testImage = await Jimp.read(fileBuffer) |
| 128 | |
| 129 | // Resize if needed (preserve aspect ratio) |
| 130 | if (originalWidth > maxDimension || originalHeight > maxDimension) { |
| 131 | if (originalWidth > originalHeight) { |
| 132 | testImage.resize({ w: maxDimension }) |
| 133 | } else { |
| 134 | testImage.resize({ h: maxDimension }) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | const testBuffer = await testImage.getBuffer('image/jpeg', { quality }) |
| 139 | const testBase64 = testBuffer.toString('base64') |
| 140 | const testBase64Size = testBase64.length |
| 141 | |
| 142 | // Track best attempt |
| 143 | if (testBase64Size < bestBase64Size) { |
| 144 | bestBase64Size = testBase64Size |
| 145 | } |
| 146 | |
| 147 | // If this attempt fits, use it |
| 148 | if (testBase64Size <= MAX_IMAGE_BASE64_SIZE) { |
| 149 | logger.debug( |
| 150 | { |
| 151 | originalSize: fileBuffer.length, |
| 152 | finalSize: testBuffer.length, |
| 153 | finalDimensions: `${testImage.bitmap.width}x${testImage.bitmap.height}`, |
| 154 | quality, |
| 155 | attempts: attemptCount, |
| 156 | }, |
| 157 | 'Image handler: Successful compression found', |
| 158 | ) |
| 159 | |
| 160 | return { |
| 161 | success: true, |
| 162 | buffer: testBuffer, |
| 163 | base64: testBase64, |
| 164 | mediaType: 'image/jpeg', |
| 165 | width: testImage.bitmap.width, |
| 166 | height: testImage.bitmap.height, |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // No compression attempt succeeded |