MCPcopy Create free account
hub / github.com/WJX20/claude-code / tryReadImageFromPath

Function tryReadImageFromPath

src/utils/imagePaste.ts:355–420  ·  view source on GitHub ↗
(
  text: string,
)

Source from the content-addressed store, hash-verified

353 * @returns Object containing the image path and base64 data, or null if not found
354 */
355export async function tryReadImageFromPath(
356 text: string,
357): Promise<(ImageWithDimensions & { path: string }) | null> {
358 // Strip terminal added spaces or quotes to dragged in paths
359 const cleanedPath = asImageFilePath(text)
360
361 if (!cleanedPath) {
362 return null
363 }
364
365 const imagePath = cleanedPath
366 let imageBuffer
367
368 try {
369 if (isAbsolute(imagePath)) {
370 imageBuffer = getFsImplementation().readFileBytesSync(imagePath)
371 } else {
372 // VSCode Terminal just grabs the text content which is the filename
373 // instead of getting the full path of the file pasted with cmd-v. So
374 // we check if it matches the filename of the image in the clipboard.
375 const clipboardPath = await getImagePathFromClipboard()
376 if (clipboardPath && imagePath === basename(clipboardPath)) {
377 imageBuffer = getFsImplementation().readFileBytesSync(clipboardPath)
378 }
379 }
380 } catch (e) {
381 logError(e as Error)
382 return null
383 }
384 if (!imageBuffer) {
385 return null
386 }
387 if (imageBuffer.length === 0) {
388 logForDebugging(`Image file is empty: ${imagePath}`, { level: 'warn' })
389 return null
390 }
391
392 // BMP is not supported by the API — convert to PNG via Sharp.
393 if (
394 imageBuffer.length >= 2 &&
395 imageBuffer[0] === 0x42 &&
396 imageBuffer[1] === 0x4d
397 ) {
398 const sharp = await getImageProcessor()
399 imageBuffer = await sharp(imageBuffer).png().toBuffer()
400 }
401
402 // Resize if needed to stay under 5MB API limit
403 // Extract extension from path for format hint
404 const ext = extname(imagePath).slice(1).toLowerCase() || 'png'
405 const resized = await maybeResizeAndDownsampleImageBuffer(
406 imageBuffer,
407 imageBuffer.length,
408 ext,
409 )
410 const base64Image = resized.buffer.toString('base64')
411
412 // Detect format from the actual file contents using magic bytes

Callers 1

usePasteHandlerFunction · 0.85

Calls 9

asImageFilePathFunction · 0.85
getFsImplementationFunction · 0.85
logForDebuggingFunction · 0.85
getImageProcessorFunction · 0.85
logErrorFunction · 0.70
toStringMethod · 0.65

Tested by

no test coverage detected