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