/ src / utils / imagePaste.ts
imagePaste.ts
 1  import { execSync } from 'child_process'
 2  import { readFileSync } from 'fs'
 3  
 4  const SCREENSHOT_PATH = '/tmp/claude_cli_latest_screenshot.png'
 5  
 6  export const CLIPBOARD_ERROR_MESSAGE =
 7    'No image found in clipboard. Use Cmd + Ctrl + Shift + 4 to copy a screenshot to clipboard.'
 8  
 9  export function getImageFromClipboard(): string | null {
10    if (process.platform !== 'darwin') {
11      // only support image paste on macOS for now
12      return null
13    }
14  
15    try {
16      // Check if clipboard has image
17      execSync(`osascript -e 'the clipboard as «class PNGf»'`, {
18        stdio: 'ignore',
19      })
20  
21      // Save the image
22      execSync(
23        `osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${SCREENSHOT_PATH}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,
24        { stdio: 'ignore' },
25      )
26  
27      // Read the image and convert to base64
28      const imageBuffer = readFileSync(SCREENSHOT_PATH)
29      const base64Image = imageBuffer.toString('base64')
30  
31      // Cleanup
32      execSync(`rm -f "${SCREENSHOT_PATH}"`, { stdio: 'ignore' })
33  
34      return base64Image
35    } catch {
36      return null
37    }
38  }