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