MCPcopy Index your code
hub / github.com/codeaashu/claude-code / maybeResizeAndDownsampleImageBuffer

Function maybeResizeAndDownsampleImageBuffer

src/utils/imageResizer.ts:169–433  ·  view source on GitHub ↗
(
  imageBuffer: Buffer,
  originalSize: number,
  ext: string,
)

Source from the content-addressed store, hash-verified

167 * Resizes image buffer to meet size and dimension constraints
168 */
169export async function maybeResizeAndDownsampleImageBuffer(
170 imageBuffer: Buffer,
171 originalSize: number,
172 ext: string,
173): Promise<ResizeResult> {
174 if (imageBuffer.length === 0) {
175 // Empty buffer would fall through the catch block below (sharp throws
176 // "Unable to determine image format"), and the fallback's size check
177 // `0 ≤ 5MB` would pass it through, yielding an empty base64 string
178 // that the API rejects with `image cannot be empty`.
179 throw new ImageResizeError('Image file is empty (0 bytes)')
180 }
181 try {
182 const sharp = await getImageProcessor()
183 const image = sharp(imageBuffer)
184 const metadata = await image.metadata()
185
186 const mediaType = metadata.format ?? ext
187 // Normalize "jpg" to "jpeg" for media type compatibility
188 const normalizedMediaType = mediaType === 'jpg' ? 'jpeg' : mediaType
189
190 // If dimensions aren't available from metadata
191 if (!metadata.width || !metadata.height) {
192 if (originalSize > IMAGE_TARGET_RAW_SIZE) {
193 // Create fresh sharp instance for compression
194 const compressedBuffer = await sharp(imageBuffer)
195 .jpeg({ quality: 80 })
196 .toBuffer()
197 return { buffer: compressedBuffer, mediaType: 'jpeg' }
198 }
199 // Return without dimensions if we can't determine them
200 return { buffer: imageBuffer, mediaType: normalizedMediaType }
201 }
202
203 // Store original dimensions (guaranteed to be defined here)
204 const originalWidth = metadata.width
205 const originalHeight = metadata.height
206
207 // Calculate dimensions while maintaining aspect ratio
208 let width = originalWidth
209 let height = originalHeight
210
211 // Check if the original file just works
212 if (
213 originalSize <= IMAGE_TARGET_RAW_SIZE &&
214 width <= IMAGE_MAX_WIDTH &&
215 height <= IMAGE_MAX_HEIGHT
216 ) {
217 return {
218 buffer: imageBuffer,
219 mediaType: normalizedMediaType,
220 dimensions: {
221 originalWidth,
222 originalHeight,
223 displayWidth: width,
224 displayHeight: height,
225 },
226 }

Callers 7

callInnerFunction · 0.85
readImageWithTokenBudgetFunction · 0.85
resizeShellImageOutputFunction · 0.85
getImageFromClipboardFunction · 0.85
tryReadImageFromPathFunction · 0.85
transformResultContentFunction · 0.85

Calls 11

getImageProcessorFunction · 0.85
logForDebuggingFunction · 0.85
classifyImageErrorFunction · 0.85
logEventFunction · 0.85
formatFileSizeFunction · 0.85
maxMethod · 0.80
logErrorFunction · 0.70
errorMessageFunction · 0.70
hashStringFunction · 0.70
resizeMethod · 0.45

Tested by

no test coverage detected