How to create new file from screenshot? (Solved)

I am trying to mimic my flow of pasting image file into a RTF note and apply it to MD note-taking:

When I am using RTF, pasting image is simple. I use shift-ctrl-cmd-4 to grab the table/picture from the source pdf/anywhere and paste whatever is in the clipboard to the RTF note directly.

I am “trying” to mimic the flow by a script to (1) grab an image (2) save the image, with a unique name, in a designated group for all images (3) copy the reference URL of the newly created image file and edit a link into the format of “![](the item link)” and put the link in the clipboard (4) paste the link to a MD note.

My script doesn’t work in one step, somehow the image is captured in the clipboard (I can see the image is captured in the clipboard through Script Debugger) , but only an empty file is created in the assets group.

I hope someone will provide valuable advice?

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

property imgAssetUUID : "7DFC0DE3-C219-4768-81F1-XXXXXXXXXXXX"

tell application id "DNtp"
	
--create a unique name based on date and time
	set dateSting to (short date string of (current date)) & "." & (time string of (current date))
	set dateSting to my findAndReplaceInText(dateSting, ":", ".")
	set dateSting to my findAndReplaceInText(dateSting, "/", ".")
	
-- capture the image by interactive selection. I believe that the default format is png
	do shell script "screencapture -ci"

-- ***** This line doesn't work. The code creates an empty file	in the right group and the right name.
-- wrong code
--	set theNewImage to create record with {name:dateSting, source:the clipboard, type:picture} in (get record with uuid imgAssetUUID)

-- correct code
	set theNewImage to paste clipboard to (get record with uuid imgAssetUUID)
	set the name of theNewImage to dateSting
	
--create an image item link and put the link in the clipboard
	set theLink to reference URL of theNewImage	
	set the clipboard to "![](" & theLink & ")"

end tell


on findAndReplaceInText(theText, theSearchString, theReplacementString)
	set AppleScript's text item delimiters to theSearchString
	set theTextItems to every text item of theText
	set AppleScript's text item delimiters to theReplacementString
	set theText to theTextItems as string
	set AppleScript's text item delimiters to ""
	return theText
end findAndReplaceInText




Got the answer from this old thread!

The script is now updated in post#1.

:+1: