Oh, your implementation is way more elegant than my script below. You really are a great developer! Can you teach me how you did it?
Here’s my script:
#!/usr/bin/env bash
Save screenshot to specified path
screencapture -i /tmp/screenshot.png
Use qlmanage to open the screenshot and bring it to the front.
qlmanage -p /tmp/screenshot.png >/dev/null 2>&1 &
Automatically copy screenshots to the clipboard.
osascript <<EOF
set imageFile to POSIX file "/tmp/screenshot.png"
set theClipboard to (read imageFile as JPEG picture)
set the clipboard to theClipboard
EOF
Optimize: Quickly check qlmanage and keep it on top.
osascript <<EOF
tell application "System Events"
set timeoutDate to (current date) + 2 -- Shorten the timeout period.
repeat while ((current date) < timeoutDate)
delay 0.1 -- Adjust the detection interval to avoid high CPU usage.
if ((name of processes) contains "qlmanage") then
tell application process "qlmanage"
set frontmost to true
end tell
exit repeat
end if
end repeat
end tell
EOF