Applescript 在处理应用程序图标上放置的图像文件时遇到问题

Applescript having problems processing a dropped image file on an Application icon

您好,我有这段代码,但在使用以下代码将图像文件拖放到 Applescript 应用程序后,我无法获得将 filename/dimensions 复制到 Mac 剪贴板的代码。是掉落物品代码不对,其余正常(图标上我只掉了一个文件)

我的代码是:

on open theDroppedItems
    
    set theCurrentItem to item a of theDroppedItems
    
    
end open

try
    
    tell application "Image Events"
        launch
        set this_image to open theCurrentItem
        copy the dimensions of this_image to {H_res, V_res}
        copy the name of this_image to originalname
        close this_image
    end tell
    
    set myvar to originalname
    set the clipboard to "src=\"" & myvar & "\"" & " width=\"" & H_res & "\"" & " width=\"" & V_res & "\""
    
end try

任何人都可以修复我的代码吗?谢谢!

on和对应的end之间的区域叫做范围

theCurrentItem 这样的局部变量只在它们声明的范围内可见。

解决方案:将与Image Events相关的代码移动到on open处理程序中

on open theDroppedItems
    set theCurrentItem to item 1 of theDroppedItems
    try
        
        tell application "Image Events"
            launch
            set this_image to open theCurrentItem as «class furl»
            copy the dimensions of this_image to {H_res, V_res}
            copy the name of this_image to originalname
            close this_image
        end tell
        
        set myvar to originalname
        set the clipboard to "src=\"" & myvar & "\"" & " width=\"" & H_res & "\"" & " width=\"" & V_res & "\""
        
    end try
end open

编辑:

另一种方法是从 Spotlight 元数据中获取维度。如果文件没有高度和宽度数据,则会将错误消息复制到剪贴板。

on run
    open (choose file with multiple selections allowed)
end run

on open theDroppedItems
    set theCurrentItem to item 1 of theDroppedItems
    set theFile to POSIX path of theCurrentItem
    try
        set {TID, text item delimiters} to {text item delimiters, "/"}
        set dimensions to paragraphs of (do shell script "mdls " & quoted form of theFile & space & "-name kMDItemPixelHeight -name kMDItemPixelWidth")
        set filename to last text item of theFile
        set text item delimiters to " = "
        tell dimensions
            set pixelsHeight to text item 2 of item 1
            set pixelsWidth to text item 2 of item 2
        end tell
        if pixelsHeight is "(null)" then error
        set text item delimiters to TID
        set the clipboard to "src=\"" & filename & "\"" & " height=\"" & pixelsHeight & "\"" & " width=\"" & pixelsWidth & "\""
    on error
        set text item delimiters to TID
        set the clipboard to "couldn't get dimensions of file " & filename
    end try
end open