AppleScript名:自然言語で指定した日時以降に作成されたファイルをSpotlight検索 |
— Created 2017-09-21 by Takaaki Naganoya — Modified 2017-09-22 by Shane Stanley — 2017 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use mdLib : script "Metadata Lib" version "2.0.0" property NSString : a reference to current application’s NSString property NSDataDetector : a reference to current application’s NSDataDetector property NSTextCheckingTypeDate : a reference to current application’s NSTextCheckingTypeDate set aDate to getDatesIn("先週の月曜日") of me –"last Monday" in Japanese log aDate set thePath to POSIX path of (path to desktop) set theFiles to mdLib’s searchFolders:{thePath} searchString:("kMDItemFSCreationDate >= %@") searchArgs:{aDate} –> returns POSIX path list on getDatesIn(aString) set anNSString to NSString’s stringWithString:aString set theDetector to NSDataDetector’s dataDetectorWithTypes:(NSTextCheckingTypeDate) |error|:(missing value) set theMatch to theDetector’s firstMatchInString:anNSString options:0 range:{0, anNSString’s |length|()} if theMatch = missing value then error "No date found with String:" & aString set theDate to theMatch’s |date|() return theDate as date end getDatesIn |
カテゴリー: file
Markdownのimglinkタグ行のリンク書き換え
Markdown書類からリンクしているローカルの画像(相対パス表記)へのリンクを書き換えるAppleScriptです。
MacDownが画像リンクの管理などは一切してくれないので、自前で(AppleScriptで)書き換えを行なっています。
ルートフォルダはフォルダ名が「–」ではじまるようにルールを(勝手に)決めており、各Markdown書類フォルダをさらに細分化した場合には、Markdown書類から画像フォルダへの相対パス指定が合わなくなってしまいます。
そこで、画像フォルダを求めてMarkdown書類の画像リンクを再計算して書き換えてみました。画像自体をルートフォルダからSpotlightで検索するようにしてもよいのですが、今回はとりあえずルールを自分で決めて自分で守っているので、このように処理してみました。
ただ、いまだにリンク画像のパスを手で書かされる(記述自体はAppleScriptでその場で計算しているので完全手書きではないですが)のには、いささかMarkdownの仕様の素朴さに呆れてしまうところです、、、、
AppleScript名:Markdownのimglinkタグ行のリンク書き換え |
— Created 2017-01-26 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use mdLib : script "Metadata Lib" version "2.0.0" –https://www.macosxautomation.com/applescript/apps/ property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property NSScanner : a reference to current application’s NSScanner property NSPredicate : a reference to current application’s NSPredicate property NSDictionary : a reference to current application’s NSDictionary property NSMutableArray : a reference to current application’s NSMutableArray property NSDataDetector : a reference to current application’s NSDataDetector property NSAttributedString : a reference to current application’s NSAttributedString property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding property NSTextCheckingTypeLink : a reference to current application’s NSTextCheckingTypeLink set origPath to POSIX path of (choose folder with prompt "Markdown書類が入っているフォルダを選択") set savePath to POSIX path of (choose folder with prompt "画像フォルダを選択") set tmp2 to NSString’s stringWithString:savePath set tmp3 to (tmp2’s lastPathComponent()) as string –Spotlightで指定フォルダ以下のMarkdown書類を検索 set aRes to mdLib’s searchFolders:{origPath} searchString:("kMDItemKind == %@ ") searchArgs:{"Markdown Document"} repeat with i in aRes –テキストエンコーディングをUTF-8でMarkDown書類テキスト読み込み set aText to (NSString’s stringWithContentsOfFile:(i) encoding:(NSUTF8StringEncoding) |error|:(missing value)) as string –Markdown記法の画像タグが入っている場合のみ処理 set repLinkURLs to {} –パス置換対象リスト(oldPath, newPathでペア) set aFreq to retFrequency(aText, "![") of me if aFreq is not equal to 0 then set bList to parseStringParagraphs(NSString’s stringWithString:aText) of me set aPredicates to NSPredicate’s predicateWithFormat_("SELF BEGINSWITH[cd] %@", "![") set cList to (bList’s filteredArrayUsingPredicate:aPredicates) as list –画像ダウンロードおよび、ダウンロードずみ画像への相対パスの計算ループ repeat with ii in cList set jj to contents of ii –画像リンクのMarkdownタグ行 set tmpLinkPath to parseStrFromTo(jj, "(", ")") of me set aStr to (NSString’s stringWithString:((contents of i) as string)) set aList to (aStr’s stringByDeletingLastPathComponent’s pathComponents()) as list of string or string set aLen to length of aList –リンク画像の相対パスを絶対パスに変換する set rStr to (NSString’s stringWithString:tmpLinkPath) set r2Str to rStr’s stringByDeletingLastPathComponent’s lastPathComponent() –フォルダ名(="9999_images") set r3Str to (rStr’s lastPathComponent()) as string –ファイル名(="fake_scriptable.png") –書籍のルートフォルダを求め、その直下にある画像フォルダを名指しで指定 repeat with i2 from aLen to 0 by -1 set j to contents of (item i2 of aList) if j begins with "–" then exit repeat end if end repeat set f1Path to (items 1 thru i2 of aList) & r2Str & r3Str set f2Path to (NSString’s pathWithComponents:f1Path) as string –MarkDown書類と移動先の画像フォルダ中の画像の相対パスを求める set newRelPath to calcRelativePathFromTwoAbsolutePaths(i, f2Path) of me set the end of repLinkURLs to {tmpLinkPath, newRelPath} end repeat –リンク書き換え copy aText to bText repeat with ii in repLinkURLs copy ii to {oldPath, newPath} set bText to repChar(bText, oldPath, newPath) of me end repeat –もともとのパスにMarkdown書類を上書き保存 set writeString to (NSString’s stringWithString:bText) set ssRes to (writeString’s writeToFile:i atomically:true encoding:(NSUTF8StringEncoding) |error|:(missing value)) end if end repeat –指定文字列内の指定キーワードの出現回数を取得する on retFrequency(origText, aKeyText) set aRes to parseByDelim(origText, aKeyText) of me return ((count every item of aRes) – 1) end retFrequency on parseByDelim(aData, aDelim) set curDelim to AppleScript’s text item delimiters set AppleScript’s text item delimiters to aDelim set dList to text items of aData set AppleScript’s text item delimiters to curDelim return dList end parseByDelim –テキストを行ごとにparseしてNSArrayに on parseStringParagraphs(anNSString) set anArray to NSMutableArray’s alloc()’s init() set aRange to current application’s NSMakeRange(0, anNSString’s |length|()) repeat while aRange’s |length|() > 0 set subRange to anNSString’s lineRangeForRange:(current application’s NSMakeRange(aRange’s location(), 0)) –行が改行コードまで取得されるので、改行コードを除外するように微調整 copy subRange to tmpRange set tmpRange’s |length| to ((subRange’s |length|()) – 1) –微調整 set aLine to anNSString’s substringWithRange:tmpRange anArray’s addObject:aLine set aRange’s location to (current application’s NSMaxRange(subRange)) set aRange’s |length| to ((aRange’s |length|()) – (subRange’s |length|())) end repeat return anArray end parseStringParagraphs on repChar(origText, targStr, repStr) set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr} set temp to text items of origText set AppleScript’s text item delimiters to repStr set res to temp as text set AppleScript’s text item delimiters to txdl return res end repChar on parseStrFromTo(aParamStr, fromStr, toStr) set theScanner to NSScanner’s scannerWithString:aParamStr set anArray to NSMutableArray’s array() repeat until (theScanner’s isAtEnd as boolean) — terminate check, return the result (aDict) to caller set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference) — skip over separator theScanner’s scanString:fromStr intoString:(missing value) set {theResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference) if theValue is missing value then set theValue to "" –>追加 — skip over separator theScanner’s scanString:toStr intoString:(missing value) anArray’s addObject:theValue end repeat if (anArray’s |count|()) as integer = 1 then return theValue as list of string or string else return anArray as list end if end parseStrFromTo –2つの絶対パス間の相対パスを求める on calcRelativePathFromTwoAbsolutePaths(aPOSIXfile as string, bPOSIXfile as string) set aStr to NSString’s stringWithString:aPOSIXfile set bStr to NSString’s stringWithString:bPOSIXfile set aList to aStr’s pathComponents() as list set bList to bStr’s pathComponents() as list set aLen to length of aList set bLen to length of bList if aLen ≥ bLen then copy aLen to aMax else copy bLen to aMax end if repeat with i from 1 to aMax set aTmp to contents of item i of aList set bTmp to contents of item i of bList if aTmp is not equal to bTmp then exit repeat end if end repeat set bbList to items i thru -1 of bList set aaItem to (length of aList) – i set tmpStr to {} repeat with ii from 1 to aaItem set the end of tmpStr to ".." end repeat set allRes to NSString’s pathWithComponents:(tmpStr & bbList) return allRes as text end calcRelativePathFromTwoAbsolutePaths |
AS構文色分け情報の重複チェック
plistから読み取ったAppleScriptの構文色分け書式データをもとに、各構文要素の指定色に重複がないかどうかチェックするAppleScriptです。
もう少しシンプルに書けそうな気もするのですが、、、
AppleScript名:AS構文色分け情報の重複チェック |
— Created 2018-04-22 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aList to {{redValue:145, greenValue:40, blueValue:144, fontName:"Osaka", fontSize:13.0}, {redValue:61, greenValue:12, blueValue:62, fontName:"Osaka", fontSize:13.0}, {redValue:14, greenValue:62, blueValue:251, fontName:"Osaka", fontSize:13.0}, {redValue:120, greenValue:52, blueValue:203, fontName:"Osaka", fontSize:13.0}, {redValue:255, greenValue:0, blueValue:0, fontName:"Osaka", fontSize:13.0}, {redValue:0, greenValue:0, blueValue:0, fontName:"Osaka", fontSize:13.0}, {redValue:145, greenValue:82, blueValue:17, fontName:"Osaka", fontSize:13.0}, {redValue:0, greenValue:0, blueValue:0, fontName:"Osaka", fontSize:13.0}, {redValue:39, greenValue:201, blueValue:201, fontName:"Osaka", fontSize:13.0}, {redValue:15, greenValue:62, blueValue:251, fontName:"Osaka", fontSize:13.0}, {redValue:31, greenValue:182, blueValue:252, fontName:"Osaka", fontSize:13.0}, {redValue:129, greenValue:58, blueValue:217, fontName:"Osaka", fontSize:13.0}, {redValue:93, greenValue:54, blueValue:146, fontName:"Osaka", fontSize:13.0}, {redValue:185, greenValue:12, blueValue:128, fontName:"Osaka", fontSize:13.0}, {redValue:25, greenValue:184, blueValue:126, fontName:"Osaka", fontSize:13.0}, {redValue:156, greenValue:145, blueValue:5, fontName:"Osaka", fontSize:13.0}, {redValue:79, greenValue:0, blueValue:136, fontName:"Osaka", fontSize:13.0}, {redValue:18, greenValue:138, blueValue:139, fontName:"Osaka", fontSize:13.0}} set cRes to chkASLexicalFormatColorConfliction(aList) of me –> false–重複があった on chkASLexicalFormatColorConfliction(aList) set anArray to current application’s NSArray’s arrayWithArray:aList set bList to (anArray’s valueForKeyPath:"redValue.stringValue") as list set cList to (anArray’s valueForKeyPath:"greenValue.stringValue") as list set dList to (anArray’s valueForKeyPath:"blueValue.stringValue") as list set colStrList to {} repeat with i from 1 to (length of bList) set bItem to contents of item i of bList set cItem to contents of item i of cList set dItem to contents of item i of dList set the end of colStrList to bItem & " " & cItem & " " & dItem end repeat set aRes to returnDuplicatesOnly(colStrList) of me if aRes is equal to {} then return true –重複が存在しなかった場合 else return false –重複があった場合 end if end chkASLexicalFormatColorConfliction on returnDuplicatesOnly(aList as list) set aSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList set bList to (aSet’s allObjects()) as list set dupList to {} repeat with i in bList set aRes to (aSet’s countForObject:i) if aRes > 1 then set the end of dupList to (contents of i) end if end repeat return dupList end returnDuplicatesOnly |
指定パスのAppleScript書類の内容をURL文字列化 v3
指定したAppleScript書類の内容を読み取って、URL文字列に変換するAppleScriptです。
Shane Stanleyによる「もうちょっと楽に書けるよ」というツッコミです。記述がシンプルになるのはいいことです。
もともと、オリジナルのScriptは10年以上昔に誰かが(Sal Soghoianあたり?)作ったもので、Cocoaの機能が利用できない時代に書かれたものでした。中途半端にCocoaの機能を利用していたので、そこを置き換えたかたちです。
AppleScript名:指定パスのAppleScript書類の内容をURL文字列化 v3 |
— Created 2018-03-28 by Takaaki Naganoya — Modified 2018-04-22 by Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "OSAKit" use framework "AppKit" set asPath to choose file of type {"com.apple.applescript.script", "com.apple.applescript.script-bundle"} set contText to getContentsOfFile(asPath) of me set encText to makeEncodedScript(contText) of me set newLinkText to "applescript://com.apple.scripteditor?action=new&script=" & encText –> "applescript://com.apple.scripteditor?action=new&script=use%20AppleScript%20version%20%222%2E4%22%0D………" –指定AppleScriptファイルのソースコードを取得する(実行専用Scriptからは取得できない) — Original Created 2014-02-23 Shane Stanley on getContentsOfFile(anAlias as {alias, string}) set anHFSpath to anAlias as string set aURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of anHFSpath) set theScript to current application’s OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value) return theScript’s source() as text end getContentsOfFile on makeEncodedScript(contText) set aStr to current application’s NSString’s stringWithString:contText set encodedStr to aStr’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet()) return encodedStr as text end makeEncodedScript |
指定パスのAppleScript書類の内容をURL文字列化 v2
指定したAppleScript書類の内容を読み取って、URL文字列に変換するAppleScriptです。
XML-RPC経由でWordPressにAppleScriptのプログラムをHTML化して掲載する時とか、PDFに対して「applescript://」カスタムプロトコルリンクを付加する処理を書いたときに使用しました。クリックすると内容がスクリプトエディタに転送されるリンクを作成するためのものです。
AppleScript名:指定パスのAppleScript書類の内容をURL文字列化 v2 |
— Created 2018-03-28 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "OSAKit" use framework "AppKit" property quotChar : string id 34 set asPath to choose file of type {"com.apple.applescript.script", "com.apple.applescript.script-bundle"} set contText to getContentsOfFile(asPath) of me set encText to makeEncodedScript(contText) of me set newLinkText to "applescript://com.apple.scripteditor?action=new&script=" & encText –> "applescript://com.apple.scripteditor?action=new&script=use%20AppleScript%20version%20%222%2E4%22%0D………" –指定AppleScriptファイルのソースコードを取得する(実行専用Scriptからは取得できない) — Original Created 2014-02-23 Shane Stanley on getContentsOfFile(anAlias as {alias, string}) set anHFSpath to anAlias as string set aURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of anHFSpath) set theScript to current application’s OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value) return theScript’s source() as text end getContentsOfFile on makeEncodedScript(contText) set delimA to "★☆temp★☆" set delimB to (retURLencodedStrings(delimA) of me) as text set aList to every paragraph of contText set aClass to class of aList if aClass = list then set aLen to length of aList else set aLen to 1 end if set aaList to {} set delim to AppleScript’s text item delimiters set AppleScript’s text item delimiters to delimA set bList to aList as text set AppleScript’s text item delimiters to delim set aaList to (retURLencodedStrings(bList) of me) as text set search_string to delimB as text set replacement_string to "%0D" as text set bList to replace_chars(aaList, search_string, replacement_string) of me return bList end makeEncodedScript on replace_chars(this_text, search_string, replacement_string) set AppleScript’s text item delimiters to the search_string set the item_list to every text item of this_text set AppleScript’s text item delimiters to the replacement_string set this_text to the item_list as string set AppleScript’s text item delimiters to "" return this_text end replace_chars on retURLencodedStrings(aText) set aStr to current application’s NSString’s stringWithString:aText set encodedStr to aStr’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s alphanumericCharacterSet()) return encodedStr as text end retURLencodedStrings |
Finderの最前面のアイコン表示ウィンドウ上の画像をY座標の情報をキーにして縦連結
Finderの最前面のWindowがアイコン表示になっている場合に、Window(Folder)内の画像ファイルをFinder上でのアイコン位置情報(Y座標のみ)を考慮して縦方向に1枚ものの画像に結合するAppleScriptです。
AppleScript名:Finderの最前面のアイコン表示ウィンドウ上の画像をY座標の情報をキーにして縦連結 |
— Created 2018-04-10 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "QuartzCore" use framework "AppKit" use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html property |NSURL| : a reference to current application’s |NSURL| property NSUUID : a reference to current application’s NSUUID property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property NSImage : a reference to current application’s NSImage property NSWorkspace : a reference to current application’s NSWorkspace property NSPNGFileType : a reference to current application’s NSPNGFileType property NSMutableArray : a reference to current application’s NSMutableArray property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey property yGap : 10 –連結時の画像間のアキ(縦方向) load framework tell application "Finder" tell front window set curView to current view if curView is not equal to icon view then display dialog "最前面のウィンドウがアイコン表示になっていないので、処理を終了します。" return end if try set posList to position of every file whose kind contains "イメージ" –"イメージ" is "image" or "picture" in Japanese set fileList to (every file whose kind contains "イメージ") as alias list –"イメージ" is "image" or "picture" in Japanese on error display dialog "最前面のウィンドウに画像ファイルが配置されていないため、処理を中止します。" return end try end tell set aList to {} set aLen to length of posList set bLen to length of fileList if aLen is not equal to bLen then return repeat with i from 1 to aLen set posItem to contents of item i of posList set aPath to POSIX path of item i of fileList set the end of aList to (posItem & aPath) end repeat end tell –> {{127, 42, "/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png"}, {302, 43, "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"}} set bList to sort2DListAscendingWithSecondItemKey(aList) of me –> {{127, 42, "/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png"}, {302, 43, "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"}} set cList to getEveryIndicatedItemsFrom2DList(bList, 3) of me –> {"/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png", "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"} –Finder最前面の画像ファイルをpathからImageを読み込んでArrayに入れる set imgList to NSMutableArray’s new() repeat with i in cList set aPath to contents of i set imgRes to (my isImageAtPath:aPath) if imgRes as boolean = true then set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath) (imgList’s addObject:aNSImage) end if end repeat –KVCで画像の各種情報をまとめて取得 set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion set maxWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.width") as real set totalHeight to (((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.height") as real) + 50 set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer –出力画像作成 set tSize to current application’s NSMakeSize(maxWidth, totalHeight + (yGap * totalCount)) set newImage to NSImage’s alloc()’s initWithSize:tSize –順次画像を新規画像に上書き set yOrig to 0 repeat with i in (imgList as list) set j to contents of i set curSize to j’s |size|() –set aRect to {0, (maxWidth – (curSize’s height())), (curSize’s width()), (curSize’s height())} set aRect to {0, (totalHeight – (curSize’s height())) – yOrig, (curSize’s width()), (curSize’s height())} set newImage to composeImage(newImage, j, aRect) of me set yOrig to yOrig + (curSize’s height()) + yGap end repeat –デスクトップにPNG形式でNSImageをファイル保存 set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/" set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png") set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me –2つのNSImageを重ね合わせ合成してNSImageで返す on composeImage(backImage, composeImage, aTargerRect) set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|()) copy aTargerRect to {x1, y1, x2, y2} newImage’s lockFocus() set v2 to system attribute "sys2" if v2 ≤ 12 then –To macOS 10.12.x set bRect to current application’s NSMakeRect(x1, y1, x2, y2) set newImageRect to current application’s CGRectZero set newImageRect’s |size| to (newImage’s |size|) else –macOS 10.13 or later set bRect to {{x1, y1}, {x2, y2}} set newImageRect to {{0, 0}, (newImage’s |size|)} end if backImage’s drawInRect:newImageRect composeImage’s drawInRect:bRect newImage’s unlockFocus() return newImage end composeImage –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep set pathString to NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –成功ならtrue、失敗ならfalseが返る end saveNSImageAtPathAsPNG –指定のパスのファイルが画像かどうかをチェック on isImageAtPath:aPath set aURL to |NSURL|’s fileURLWithPath:aPath set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value) return (NSImage’s imageTypes()’s containsObject:theValue) as boolean end isImageAtPath: on sort2DListAscendingWithSecondItemKey(aList as list) set sortIndexList to {1} –Key Item id: begin from 0 set sortOrders to {true} –ascending = true set sortTypes to {"compare:"} set resList to (current application’s SMSForder’s subarraysIn:(aList) sortedByIndexes:sortIndexList ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list return resList end sort2DListAscendingWithSecondItemKey –2D Listの各要素から、指定アイテムの要素だけを取り出してリストで返す on getEveryIndicatedItemsFrom2DList(aList as list, anItem as integer) –this item No. begins from 1 set outList to {} repeat with i in aList set j to contents of item anItem of i set the end of outList to j end repeat return outList end getEveryIndicatedItemsFrom2DList |
Finderの最前面のアイコン表示ウィンドウ上の画像をX座標の情報をキーにして横連結
Finderの最前面のWindowがアイコン表示になっている場合に、Window(Folder)内の画像ファイルをFinder上でのアイコン位置情報(X座標のみ)を考慮して横方向に1枚ものの画像に結合するAppleScriptです。
Blog掲載時に利用するために、Finder上で選択中の複数の画像ファイルを1枚ものの画像に(横方向/縦方向に)連結するAppleScriptを便利に使っています(ただし、「動けばいいや」程度で雑に作ったので、普段よりもやっつけ度がかなり高い、、、)。
ただし、画像の並び順については「たぶん、作成日時の古い順」に連結されるといった具合に明示的に並び順を指定できるものではなかったので、本Scriptを作ってみました。 –> Demo Movie
Finder上でicon viewに指定したWindow(Folder)内でLeft–>Rightの順に(X座標のみ評価)座標値をソートして連結します。
AppleScript名:Finderの最前面のアイコン表示ウィンドウ上の画像をX座標の情報をキーにして横連結 |
— Created 2018-04-10 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "QuartzCore" use framework "AppKit" use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html property |NSURL| : a reference to current application’s |NSURL| property NSUUID : a reference to current application’s NSUUID property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property NSImage : a reference to current application’s NSImage property NSWorkspace : a reference to current application’s NSWorkspace property NSPNGFileType : a reference to current application’s NSPNGFileType property NSMutableArray : a reference to current application’s NSMutableArray property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey property xGap : 10 –連結時の画像間のアキ(横方向) load framework tell application "Finder" tell front window set curView to current view if curView is not equal to icon view then display dialog "最前面のウィンドウがアイコン表示になっていないので、処理を終了します。" return end if try set posList to position of every file whose kind contains "イメージ" –"イメージ" is "image" or "picture" in Japanese set fileList to (every file whose kind contains "イメージ") as alias list –"イメージ" is "image" or "picture" in Japanese on error display dialog "最前面のウィンドウに画像ファイルが配置されていないため、処理を中止します。" return end try end tell set aList to {} set aLen to length of posList set bLen to length of fileList if aLen is not equal to bLen then return repeat with i from 1 to aLen set posItem to contents of item i of posList set aPath to POSIX path of item i of fileList set the end of aList to (posItem & aPath) end repeat end tell –> {{127, 42, "/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png"}, {302, 43, "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"}} set bList to sort2DListAscendingWithFirstItemKey(aList) of me –> {{127, 42, "/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png"}, {302, 43, "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"}} set cList to getEveryIndicatedItemsFrom2DList(bList, 3) of me –> {"/Users/me/Desktop/名称未設定フォルダ/000_keynote_print.png", "/Users/me/Desktop/名称未設定フォルダ/999_indesign_print.png"} –Finder最前面の画像ファイルをpathからImageを読み込んでArrayに入れる set imgList to NSMutableArray’s new() repeat with i in cList set aPath to contents of i set imgRes to (my isImageAtPath:aPath) if imgRes as boolean = true then set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath) (imgList’s addObject:aNSImage) end if end repeat –KVCで画像の各種情報をまとめて取得 set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion set maxHeight to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.height") as real set totalWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.width") as real set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer –出力画像作成 set tSize to current application’s NSMakeSize((totalWidth + (xGap * totalCount)), maxHeight) set newImage to NSImage’s alloc()’s initWithSize:tSize –順次画像を新規画像に上書き set xOrig to 0 repeat with i in (imgList as list) set j to contents of i set curSize to j’s |size|() set aRect to {xOrig, (maxHeight – (curSize’s height())), (curSize’s width()), (curSize’s height())} set newImage to composeImage(newImage, j, aRect) of me set xOrig to xOrig + (curSize’s width()) + xGap end repeat –デスクトップにPNG形式でNSImageをファイル保存 set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/" set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png") set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me –2つのNSImageを重ね合わせ合成してNSImageで返す on composeImage(backImage, composeImage, aTargerRect) set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|()) copy aTargerRect to {x1, y1, x2, y2} newImage’s lockFocus() set v2 to system attribute "sys2" if v2 ≤ 12 then –To macOS 10.12.x set bRect to current application’s NSMakeRect(x1, y1, x2, y2) set newImageRect to current application’s CGRectZero set newImageRect’s |size| to (newImage’s |size|) else –macOS 10.13 or later set bRect to {{x1, y1}, {x2, y2}} set newImageRect to {{0, 0}, (newImage’s |size|)} end if backImage’s drawInRect:newImageRect composeImage’s drawInRect:bRect newImage’s unlockFocus() return newImage end composeImage –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep set pathString to NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –成功ならtrue、失敗ならfalseが返る end saveNSImageAtPathAsPNG –指定のパスのファイルが画像かどうかをチェック on isImageAtPath:aPath set aURL to |NSURL|’s fileURLWithPath:aPath set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value) return (NSImage’s imageTypes()’s containsObject:theValue) as boolean end isImageAtPath: on sort2DListAscendingWithFirstItemKey(aList as list) set sortIndexList to {0} –Key Item id: begin from 0 set sortOrders to {true} –ascending = true set sortTypes to {"compare:"} set resList to (current application’s SMSForder’s subarraysIn:(aList) sortedByIndexes:sortIndexList ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list return resList end sort2DListAscendingWithFirstItemKey –2D Listの各要素から、指定アイテムの要素だけを取り出してリストで返す on getEveryIndicatedItemsFrom2DList(aList as list, anItem as integer) –this item No. begins from 1 set outList to {} repeat with i in aList set j to contents of item anItem of i set the end of outList to j end repeat return outList end getEveryIndicatedItemsFrom2DList |
エイリアス書類からオリジナルファイルの情報を取得する
指定のエイリアス書類から、オリジナルファイルの情報を取得するAppleScriptです。
オリジナルファイルを求める処理、というよりはエイリアス書類のリンク切れ(実体ファイルの存在)チェックを行うというのが「隠れた目的」です。
「エイリアス書類」とaliasは別物なので注意が必要です。どちらかといえば説明に注意が必要といったところなのかも???
本Blogでは両者を「エイリアス書類」「alias」と区別して記述しています。
AppleScript名:エイリアス書類からオリジナルファイルの情報を取得する |
set aFile to choose file
tell application "Finder" try set origI to (original item of aFile) as alias on error –エイリアス書類のオリジナルファイルが削除されていた場合(リンク切れ。オリジナル書類が削除されていた場合)にはエラーになる set origI to false end try end tell |
指定フォルダのサブフォルダの中からYYYY_MM_DDで最新のものを抽出してFinderでオープン
指定フォルダ以下に存在するYYYY/MM/DDの3階層のフォルダで最新のものを抽出してFinder上で選択状態にするAppleScriptです。
もともと、Safariのダウンロードフォルダに対してFolder Action Scriptを設定して、当日のYYYY/MM/DDの3階層のフォルダを作成してそこにダウンロードしたファイルを移動する処理を行っていました。
その最新フォルダをFinder上で表示する必要があったので、作成したものです。
AppleScriptのPOSIX pathとCocoaのPOSIX path(NSString)では末尾のスラッシュの有無が異なっており、専用ルーチンから切り分けて汎用ルーチンとして使いまわそうとして久しぶりにハマりました。
AppleScript名:指定フォルダのサブフォルダの中からYYYY_MM_DDで最新のものを抽出してFinderでオープン |
— Created 2018-04-09 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html set sDL to POSIX path of (choose folder) –> "/Users/me/Downloads/"–AppleScript HFS to POSIX path (ends with slash) retLatestYYYYMMDDFolderUnder(sDL, 2017) of me on retLatestYYYYMMDDFolderUnder(aPOSIXFolderPath as string, minYYYY as integer) load framework –load BridgePlus framework if aPOSIXFolderPath ends with "/" then set aPOSIXFolderPath to text 1 thru -2 of aPOSIXFolderPath end if –> "/Users/maro/Downloads"–Cocoa POSIX path (does not end with) set sList to (current application’s NSString’s stringWithString:aPOSIXFolderPath)’s pathComponents() as list –> {"/", "Users", "me", "Downloads"} set sLen to length of sList –> 4 set fListRes to getFolderspathComponentsIn(aPOSIXFolderPath) of me –> {{"/", "Users", "me", "Downloads", "2016"}, {"/", "Users", "me", "Downloads", "2018", "03", "20"}…} set anArray to current application’s NSMutableArray’s arrayWithArray:fListRes set predStr to "SELF[SIZE] = " & (sLen + 3) as string set aPredicate to current application’s NSPredicate’s predicateWithFormat:predStr set t1Array to (anArray’s filteredArrayUsingPredicate:aPredicate) –> {{"/", "Users", "me", "Downloads", "2018", "03", "20"}…} set predStr1 to ("SELF[" & (sLen) as string) & "].floatValue >= " & (minYYYY as string) & " && SELF[" & ((sLen + 1) as string) & "].floatValue >= 1 && SELF[" & ((sLen + 2) as string) & "].floatValue >= 1" set aPredicate1 to current application’s NSPredicate’s predicateWithFormat:predStr1 set t2Array to (t1Array’s filteredArrayUsingPredicate:aPredicate1) as list –YYYY, MM, DDでそれぞれ降順ソート。最新のものを取得 set theResult to current application’s SMSForder’s subarraysIn:t2Array sortedByIndexes:{sLen, sLen + 1, sLen + 2} ascending:{false, false, false} sortTypes:{"compare:", "compare:", "compare:"} |error|:(missing value) if (theResult as list = {} or theResult = missing value) then return {} –最新のYYYY/MM/DDフォルダを取得してFinder上で選択表示 set theNewest to contents of first item of (theResult as list) set theNewestStr to (current application’s NSString’s pathWithComponents:theNewest) set parentPath to theNewestStr’s stringByDeletingLastPathComponent() set aRes to current application’s NSWorkspace’s sharedWorkspace()’s selectFile:theNewestStr inFileViewerRootedAtPath:parentPath end retLatestYYYYMMDDFolderUnder on getFolderspathComponentsIn(posixPath) script spd property allItems : {} end script set allItems of spd to {} set theNSURL to current application’s |NSURL|’s fileURLWithPath:posixPath set theNSFileManager to current application’s NSFileManager’s new() — get URL enumerator set theNSFileEnumerator to theNSFileManager’s enumeratorAtURL:theNSURL includingPropertiesForKeys:{current application’s NSURLIsDirectoryKey, current application’s NSURLIsPackageKey} options:((current application’s NSDirectoryEnumerationSkipsPackageDescendants) + (current application’s NSDirectoryEnumerationSkipsHiddenFiles as integer)) errorHandler:(missing value) — get all items from enumerator set (allItems of spd) to theNSFileEnumerator’s allObjects() set theFolders to {} — to store folders — loop through repeat with i from 1 to count of (allItems of spd) — is it a directory? set {theResult, isDirectory} to ((item i of (allItems of spd))’s getResourceValue:(reference) forKey:(current application’s NSURLIsDirectoryKey) |error|:(missing value)) if isDirectory as boolean = true then set {theResult, isPackage} to ((item i of (allItems of spd))’s getResourceValue:(reference) forKey:(current application’s NSURLIsPackageKey) |error|:(missing value)) — is it not a package? if not isPackage as boolean = true then set end of theFolders to (item i of (allItems of spd))’s pathComponents() as list –parse each directory into list end if end if end repeat return theFolders end getFolderspathComponentsIn |
Finder上で選択中の画像を縦方向に連結 v1
Finder上で選択中の画像ファイルを縦方向に連結して結果をデスクトップ上に出力するAppleScriptです。
AppleScript名:Finder上で選択中の画像を縦方向に連結 v1 |
— Created 2017-11-21 by Takaaki Naganoya — Modified 2018-04-06 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" — El Capitan (10.11) or later use framework "Foundation" use framework "QuartzCore" use framework "AppKit" use scripting additions property |NSURL| : a reference to current application’s |NSURL| property NSUUID : a reference to current application’s NSUUID property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property NSImage : a reference to current application’s NSImage property NSWorkspace : a reference to current application’s NSWorkspace property NSPNGFileType : a reference to current application’s NSPNGFileType property NSMutableArray : a reference to current application’s NSMutableArray property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey property yGap : 10 –連結時の画像間のアキ(横方向) tell application "Finder" set aSel to selection as alias list if aSel = {} or aSel = "" then return end tell –選択した画像をArrayに入れる set imgList to NSMutableArray’s new() repeat with i in aSel set aPath to POSIX path of i set imgRes to (my isImageAtPath:aPath) if imgRes as boolean = true then set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath) (imgList’s addObject:aNSImage) end if end repeat –KVCで画像の各種情報をまとめて取得 set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion set maxWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.width") as real set totalHeight to (((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.height") as real) + 50 set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer –出力画像作成 set tSize to current application’s NSMakeSize(maxWidth, totalHeight + (yGap * totalCount)) set newImage to NSImage’s alloc()’s initWithSize:tSize –順次画像を新規画像に上書き set yOrig to 0 repeat with i in (imgList as list) set j to contents of i set curSize to j’s |size|() –set aRect to {0, (maxWidth – (curSize’s height())), (curSize’s width()), (curSize’s height())} set aRect to {0, (totalHeight – (curSize’s height())) – yOrig, (curSize’s width()), (curSize’s height())} set newImage to composeImage(newImage, j, aRect) of me set yOrig to yOrig + (curSize’s height()) + yGap end repeat –デスクトップにPNG形式でNSImageをファイル保存 set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/" set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png") set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me –2つのNSImageを重ね合わせ合成してNSImageで返す on composeImage(backImage, composeImage, aTargerRect) set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|()) copy aTargerRect to {x1, y1, x2, y2} newImage’s lockFocus() set v2 to system attribute "sys2" if v2 ≤ 12 then –To macOS 10.12.x set bRect to current application’s NSMakeRect(x1, y1, x2, y2) set newImageRect to current application’s CGRectZero set newImageRect’s |size| to (newImage’s |size|) else –macOS 10.13 or later set bRect to {{x1, y1}, {x2, y2}} set newImageRect to {{0, 0}, (newImage’s |size|)} end if backImage’s drawInRect:newImageRect composeImage’s drawInRect:bRect newImage’s unlockFocus() return newImage end composeImage –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep set pathString to NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –成功ならtrue、失敗ならfalseが返る end saveNSImageAtPathAsPNG –指定のパスのファイルが画像かどうかをチェック on isImageAtPath:aPath set aURL to |NSURL|’s fileURLWithPath:aPath set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value) return (NSImage’s imageTypes()’s containsObject:theValue) as boolean end isImageAtPath: |
配列に入れた画像を類似度でソートする
ターゲット画像に対して配列に入れた複数の画像を類似度をキーにしてソートするAppleScriptです。
最も類似度が高いと思われる画像をデスクトップにPNG形式で書き出します。
CocoaImageHashing.framework (To ~/Library/Frameworks/)
AppleScript名:配列に入れた画像を類似度でソートする |
— Created 2016-10-30 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "CocoaImageHashing" –https://github.com/ameingast/cocoaimagehashing –From Example: "Sorting an NSArray containing image data" –比較元の画像を選択 set baseData to retDataFromPath(POSIX path of (choose file {"public.image"})) of me –比較対象のデータを選択 set aData to retDataFromPath(POSIX path of (choose file {"public.image"})) of me set bData to retDataFromPath(POSIX path of (choose file {"public.image"})) of me set cData to retDataFromPath(POSIX path of (choose file {"public.image"})) of me set aList to {aData, bData, cData} set anArray to current application’s NSMutableArray’s arrayWithArray:aList –配列に入れられた画像を類似度でソートする set aRes to (current application’s OSImageHashing’s sharedInstance()’s sortedArrayUsingImageSimilartyComparator:baseData forArray:anArray) –最も類似度の高い画像データを取り出す set firstObj to aRes’s objectAtIndex:0 set anImage to current application’s NSImage’s alloc()’s initWithData:firstObj –確認のため、デスクトップにPNG形式で最も類似度の高い画像を書き出す set aFolder to POSIX path of (path to desktop folder) set fRes to retUUIDfilePathFromFolder(aFolder, "png") of me set sRes to saveNSImageAtPathAsPNG(anImage, fRes) of me on retUUIDfilePathFromFolder(aFolder, aEXT) set aUUIDstr to (current application’s NSUUID’s UUID()’s UUIDString()) as string set aPath to ((current application’s NSString’s stringWithString:aFolder)’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT return aPath end retUUIDfilePathFromFolder –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –true/false end saveNSImageAtPathAsPNG on retDataFromPath(aFile) set aURL to current application’s |NSURL|’s fileURLWithPath:aFile set aData to current application’s NSData’s dataWithContentsOfURL:aURL return aData end retDataFromPath |
2つの画像が類似しているかを判定
2つの画像が類似しているかどうかを判定するAppleScriptです。
CocoaImageHashing.framework (To ~/Library/Frameworks/)
AppleScript名:2つの画像が類似しているかを判定 |
— Created 2016-10-30 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "CocoaImageHashing" –https://github.com/ameingast/cocoaimagehashing –From Example: "Comparing two images for similarity" set aFile to POSIX path of (choose file {"public.image"}) set bFile to POSIX path of (choose file {"public.image"}) set aRes to checkSimiliality(aFile, bFile) of me –> true / false on checkSimiliality(aFile, bFile) set aURL to current application’s |NSURL|’s fileURLWithPath:aFile set bURL to current application’s |NSURL|’s fileURLWithPath:bFile set aData to current application’s NSData’s dataWithContentsOfURL:aURL set bData to current application’s NSData’s dataWithContentsOfURL:bURL set aRes to (current application’s OSImageHashing’s sharedInstance()’s compareImageData:aData |to|:bData) as boolean return aRes end checkSimiliality |
NSImageをリサイズ(アンチエイリアス解除)pattern 4
指定ファイルをNSImageに読み込んで、アンチエイリアスを使用せずに指定倍率に拡大するAppleScriptです。
▲Original & Resized Image (x10)
AppleScript名:NSImageをリサイズ(アンチエイリアス解除)pattern 4 |
— Created 2017-02-03 by Takaaki Naganoya — Modified 2017-03-22 by Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set aPath to POSIX path of (choose file of type {"public.image"} with prompt "Select Image file to scale up (x10)") set aNSImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aPath set resizedImg to my resizeNSImageWithoutAntlialias:aNSImage toScale:10 set aDesktopPath to (current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/" set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png") set fRes to saveNSImageAtPathAsPNG(resizedImg, savePath) of me –NSImageを指定倍率で拡大(アンチエイリアス解除状態で) on resizeNSImageWithoutAntlialias:aSourceImg toScale:imgScale set aSize to aSourceImg’s |size|() set aWidth to (aSize’s width) * imgScale set aHeight to (aSize’s height) * imgScale set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:aWidth pixelsHigh:aHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(current application’s NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0 set newSize to {width:aWidth, height:aHeight} aRep’s setSize:newSize current application’s NSGraphicsContext’s saveGraphicsState() set theContext to current application’s NSGraphicsContext’s graphicsContextWithBitmapImageRep:aRep current application’s NSGraphicsContext’s setCurrentContext:theContext theContext’s setShouldAntialias:false theContext’s setImageInterpolation:(current application’s NSImageInterpolationNone) aSourceImg’s drawInRect:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeCopy) fraction:(1.0) current application’s NSGraphicsContext’s restoreGraphicsState() set newImg to current application’s NSImage’s alloc()’s initWithSize:newSize newImg’s addRepresentation:aRep return newImg end resizeNSImageWithoutAntlialias:toScale: –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes end saveNSImageAtPathAsPNG |
画像中の色の置き換え
指定画像中の指定色を置き換えるAppleScriptです。
replaceColorKit.framework (To ~/Library/Frameworks/)
▲Color Replaced Image & Original (Yellow)
AppleScript名:画像中の色の置き換え |
— Created 2017-04-23 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "replaceColorKit" –https://github.com/braginets/NSImage-replace-color use framework "AppKit" set aThreshold to 0.2 set aFile to POSIX path of (choose file of type {"public.image"}) set anImage to (current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile) set aColor to makeNSColorFromRGBA255val(246, 253, 0, 255) of me set bColor to makeNSColorFromRGBA255val(154, 154, 154, 255) of me set bImage to (anImage’s replaceColor:aColor withColor:bColor withThreshold:aThreshold) set aDesktopPath to ((current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/") set savePath to (aDesktopPath’s stringByAppendingString:((current application’s NSString’s stringWithString:(aThreshold as string))’s stringByAppendingString:".png")) set fRes to saveNSImageAtPathAsPNG(bImage, savePath) of me –0〜255の数値でNSColorを作成する on makeNSColorFromRGBA255val(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer) set aRedCocoa to (redValue / 255) as real set aGreenCocoa to (greenValue / 255) as real set aBlueCocoa to (blueValue / 255) as real set aAlphaCocoa to (alphaValue / 255) as real set aColor to current application’s NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa return aColor end makeNSColorFromRGBA255val –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes end saveNSImageAtPathAsPNG |
指定画像の余白の自動トリミング
指定画像の余白トリミングを自動で行うAppleScriptです。
KGPixelBoundsClipKit.framework (To ~/Library/Frameworks/)
AppleScript名:指定画像の余白の自動トリミング |
— Created 2017-04-26 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" use framework "KGPixelBoundsClipKit" –https://github.com/kgn/KGPixelBoundsClip set aFile to POSIX path of (choose file of type {"public.image"}) set anImage to (current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile) set bImage to anImage’s imageClippedToPixelBounds() set aDesktopPath to (current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/" set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png") set fRes to saveNSImageAtPathAsPNG(bImage, savePath) of me –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes end saveNSImageAtPathAsPNG |
NSImageの垂直、水平反転
NSImageの垂直方向、水平方向の反転を行うAppleScriptです。
▲Original Image
▲Horizontal Flipped Image
▲Vertical Flipped Image
AppleScript名:NSImageの垂直、水平反転 |
— Created 2017-07-25 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" –https://stackoverflow.com/questions/10936590/flip-nsimage-on-both-axes set aFile to POSIX path of (choose file of type {"public.image"} with prompt "Select an Image") set currentImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile set imgRes to flipImageVertically(currentImage) of me set fRes to retUUIDfilePath(aFile, "png") of me set sRes to saveNSImageAtPathAsPNG(imgRes, fRes) of me –水平方向の画像反転 on flipImageHorizontally(anNSImage) set transform to current application’s NSAffineTransform’s transform() set dimList to anNSImage’s |size|() set flipList to {-1.0, 0.0, 0.0, 1.0, dimList’s width, 0.0} set tmpImage to current application’s NSImage’s alloc()’s initWithSize:(dimList) tmpImage’s lockFocus() transform’s setTransformStruct:flipList transform’s concat() anNSImage’s drawAtPoint:(current application’s NSMakePoint(0, 0)) fromRect:(current application’s NSMakeRect(0, 0, dimList’s width, dimList’s height)) operation:(current application’s NSCompositeCopy) fraction:1.0 tmpImage’s unlockFocus() return tmpImage end flipImageHorizontally –垂直方向の画像反転 on flipImageVertically(anNSImage) set transform to current application’s NSAffineTransform’s transform() set dimList to anNSImage’s |size|() set flipList to {1.0, 0.0, 0.0, -1.0, 0.0, dimList’s height} set tmpImage to current application’s NSImage’s alloc()’s initWithSize:(dimList) tmpImage’s lockFocus() transform’s setTransformStruct:flipList transform’s concat() anNSImage’s drawAtPoint:(current application’s NSMakePoint(0, 0)) fromRect:(current application’s NSMakeRect(0, 0, dimList’s width, dimList’s height)) operation:(current application’s NSCompositeCopy) fraction:1.0 tmpImage’s unlockFocus() return tmpImage end flipImageVertically on retUUIDfilePath(aPath, aEXT) set aUUIDstr to (current application’s NSUUID’s UUID()’s UUIDString()) as string set aPath to ((current application’s NSString’s stringWithString:aPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT return aPath end retUUIDfilePath –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –true/false end saveNSImageAtPathAsPNG |
単色画像(アルファ値必要)に色を指定して塗りつぶし
単色画像に色を指定して塗りつぶしを行うAppleScriptです。
▲Original Image
▲Result Image
AppleScript名:単色画像(アルファ値必要)に色を指定して塗りつぶし |
— Created 2017-04-24 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" use framework "QuartzCore" –http://piyocast.com/as/archives/4615 set aFile to POSIX path of (choose file of type "public.image") set aColor to makeNSColorFromRGBA255val(0, 0, 255, 255) of me set aColoredImage to fillColorWithImage(aFile, aColor) of me set aDesktopPath to ((current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/") set savePath to (aDesktopPath’s stringByAppendingString:((current application’s NSString’s stringWithString:"testOverlay")’s stringByAppendingString:".png")) set fRes to saveNSImageAtPathAsPNG(aColoredImage, savePath) of me on fillColorWithImage(aFile, aColor) set anImage to (current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile) set aSize to anImage’s |size|() set aWidth to (aSize’s width) set aHeight to (aSize’s height) set colordImage to makeNSImageWithFilledWithColor(aWidth, aHeight, aColor) of me colordImage’s lockFocus() anImage’s drawAtPoint:{0, 0} fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeDestinationIn) fraction:1.0 colordImage’s unlockFocus() return colordImage end fillColorWithImage –指定サイズの画像を作成し、指定色で塗ってファイル書き出し on makeNSImageWithFilledWithColor(aWidth, aHeight, fillColor) set anImage to current application’s NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight)) anImage’s lockFocus() — set theRect to {{x:0, y:0}, {height:aHeight, width:aWidth}} set theNSBezierPath to current application’s NSBezierPath’s bezierPath theNSBezierPath’s appendBezierPathWithRect:theRect — fillColor’s |set|() –色設定 theNSBezierPath’s fill() –ぬりつぶし — anImage’s unlockFocus() — return anImage end makeNSImageWithFilledWithColor on makeNSColorFromRGBA255val(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer) set aRedCocoa to (redValue / 255) as real set aGreenCocoa to (greenValue / 255) as real set aBlueCocoa to (blueValue / 255) as real set aAlphaCocoa to (alphaValue / 255) as real set aColor to current application’s NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa return aColor end makeNSColorFromRGBA255val –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –成功ならtrue、失敗ならfalseが返る end saveNSImageAtPathAsPNG |
画像+文字作成テスト_v4
指定サイズの画像に対して指定の文字を描画して指定ファイル名のPNG画像を書き出すAppleScriptです。
AppleScript名:画像+文字作成テスト_v4 |
— Created 2015-07-31 by Takaaki Naganoya — Modified 2015-08-01 by Shane Stanley — Modified 2017-11-19 by Takaaki Naganoya / macOS 10.13のバグに対応 use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "AppKit" set aWidth to 400.0 –幅 set aHeight to 200.0 –高さ set outPath to "~/Desktop/test.png" –書き出し先のファイルパス set fillColor to current application’s NSColor’s blackColor –塗り色 set drawColor to current application’s NSColor’s whiteColor –文字色 set aText to "ぴよまるソフトウェア" set {xPos, yPos} to {1, 5} –新規画像を作成して背景を塗る set anImage to makeImageWithFilledColor(aWidth, aHeight, outPath, fillColor) of me –画像に文字を塗る(参照渡し(call by reference)で、結果はaImage1に入る) drawStringsOnImage(anImage, aText, "HiraKakuStd-W8", 36.0, drawColor, xPos, yPos) of me –ファイル保存 set aRes to saveImageRepAtPathAsPNG(anImage, outPath) of me –画像のうえに指定の文字を描画して画像を返す on drawStringsOnImage(anImage, aText, aFontName, aPoint, drawColor) set retinaF to (current application’s NSScreen’s mainScreen()’s backingScaleFactor()) as real –> 2.0 (Retina) / 1.0 (Non Retina) set aString to current application’s NSString’s stringWithString:aText set aDict to current application’s NSDictionary’s dictionaryWithObjects:{current application’s NSFont’s fontWithName:aFontName |size|:aPoint, drawColor} forKeys:{current application’s NSFontAttributeName, current application’s NSForegroundColorAttributeName} set imageSize to anImage’s |size|() set textSize to aString’s sizeWithAttributes:aDict set xPos to ((width of imageSize) – (width of textSize)) / 2 / retinaF set yPos to ((height of imageSize) – (height of textSize)) / 2 / retinaF –文字描画開始 anImage’s lockFocus() aString’s drawAtPoint:(current application’s NSMakePoint(xPos, yPos)) withAttributes:aDict anImage’s unlockFocus() end drawStringsOnImage –指定サイズの画像を作成し、背景を指定色で塗る on makeImageWithFilledColor(aWidth, aHeight, outPath, fillColor) set anImage to current application’s NSImage’s alloc()’s initWithSize:(current application’s NSMakeSize(aWidth, aHeight)) –描画開始 anImage’s lockFocus() set theRect to {{x:0, y:0}, {width:aWidth, height:aHeight}} set theNSBezierPath to current application’s NSBezierPath’s bezierPath theNSBezierPath’s appendBezierPathWithRect:theRect fillColor’s |set|() –色設定 theNSBezierPath’s fill() –ぬりつぶし anImage’s unlockFocus() –描画ここまで return anImage –画像を返す end makeImageWithFilledColor –画像を指定パスにPNG形式で保存 on saveImageRepAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep –書き出しファイルパス情報を作成 set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() –書き出し set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –成功ならtrue、失敗ならfalseが返る end saveImageRepAtPathAsPNG |
DSCaptureで画面キャプチャ
shellのscreencaptureコマンドを使わずにフレームワーク経由で画面キャプチャを行うAppleScriptです。
オープンソースのDSCaptureを利用しており、キャプチャ内容をファイルではなくNSImageに格納できる(メモリ上に、ファイルI/Oを経由せずに取得できる)ので、割と使い手があります。とくに、ファイルI/Oに対してはセキュリティ機能による制約が多いために、メモリ上で処理できることのメリットははかりしれません。
本サンプルScriptでは、動作確認のためにキャプチャ内容をファイルに保存していますが、本来このFrameworkの性格からいえばファイル保存するのは「特徴」を台無しにしています。キャプチャしたイメージ(NSImage)をメモリ上で加工するのに向いています。
–> Download DSCapture.framework (To ~/Library/Frameworks/)
AppleScript名:DSCaptureで画面キャプチャ |
— Created 2017-01-16 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "DSCapture" –https://github.com/kiding/DSCapture.framework use framework "AppKit" –Full Screen (Every Display) set aCapt to current application’s DSCapture’s sharedCapture()’s |full|()’s captureWithTarget:me selector:"displayCaptureData:" useCG:false –Selected Area (Selected Area Only by user operation) –set bCapt to current application’s DSCapture’s sharedCapture()’s |selection|()’s captureWithTarget:me selector:"displayCaptureData:" useCG:false –Delegate Handler on displayCaptureData:aSender set aCount to aSender’s |count|() repeat with i from 0 to (aCount – 1) set anImage to (aSender’s imageAtIndex:i) –Make Save Image Path set aDesktopPath to ((current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/") set savePath to (aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")) saveNSImageAtPathAsPNG(anImage, savePath) of me end repeat end displayCaptureData: –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep set pathString to current application’s NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –成功ならtrue、失敗ならfalseが返る end saveNSImageAtPathAsPNG |
Finder上で選択中の画像を横方向に連結 v4
Finder上で選択中の画像ファイルを横方向に連結して結果をデスクトップ上に出力するAppleScriptです。
Shane Stanleyから「macOS 10.13で動かないよ」とツッコミが入ってmacOS 10.13に対応するよう書き換えたものです。
AppleScript名:Finder上で選択中の画像を横方向に連結 v4 |
— Created 2017-11-21 by Takaaki Naganoya — Modified 2018-04-06 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" — El Capitan (10.11) or later use framework "Foundation" use framework "QuartzCore" use framework "AppKit" use scripting additions property |NSURL| : a reference to current application’s |NSURL| property NSUUID : a reference to current application’s NSUUID property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property NSImage : a reference to current application’s NSImage property NSWorkspace : a reference to current application’s NSWorkspace property NSPNGFileType : a reference to current application’s NSPNGFileType property NSMutableArray : a reference to current application’s NSMutableArray property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey property xGap : 10 –連結時の画像間のアキ(横方向) tell application "Finder" set aSel to selection as alias list if aSel = {} or aSel = "" then return end tell –選択した画像をArrayに入れる set imgList to NSMutableArray’s new() repeat with i in aSel set aPath to POSIX path of i set imgRes to (my isImageAtPath:aPath) if imgRes as boolean = true then set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath) (imgList’s addObject:aNSImage) end if end repeat –KVCで画像の各種情報をまとめて取得 set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion set maxHeight to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.height") as real set totalWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.width") as real set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer –出力画像作成 set tSize to current application’s NSMakeSize((totalWidth + (xGap * totalCount)), maxHeight) set newImage to NSImage’s alloc()’s initWithSize:tSize –順次画像を新規画像に上書き set xOrig to 0 repeat with i in (imgList as list) set j to contents of i set curSize to j’s |size|() set aRect to {xOrig, (maxHeight – (curSize’s height())), (curSize’s width()), (curSize’s height())} set newImage to composeImage(newImage, j, aRect) of me set xOrig to xOrig + (curSize’s width()) + xGap end repeat –デスクトップにPNG形式でNSImageをファイル保存 set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/" set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png") set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me –2つのNSImageを重ね合わせ合成してNSImageで返す on composeImage(backImage, composeImage, aTargerRect) set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|()) copy aTargerRect to {x1, y1, x2, y2} newImage’s lockFocus() set v2 to system attribute "sys2" if v2 ≤ 12 then –To macOS 10.12.x set bRect to current application’s NSMakeRect(x1, y1, x2, y2) set newImageRect to current application’s CGRectZero set newImageRect’s |size| to (newImage’s |size|) else –macOS 10.13 or later set bRect to {{x1, y1}, {x2, y2}} set newImageRect to {{0, 0}, (newImage’s |size|)} end if backImage’s drawInRect:newImageRect composeImage’s drawInRect:bRect newImage’s unlockFocus() return newImage end composeImage –NSImageを指定パスにPNG形式で保存 on saveNSImageAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep set pathString to NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value)) set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean return aRes –成功ならtrue、失敗ならfalseが返る end saveNSImageAtPathAsPNG –指定のパスのファイルが画像かどうかをチェック on isImageAtPath:aPath set aURL to |NSURL|’s fileURLWithPath:aPath set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value) return (NSImage’s imageTypes()’s containsObject:theValue) as boolean end isImageAtPath: |