20260513

[AppleScript] swift+ASで画像のピクセルサイズと解像度の取得

[AppleScript] swift+ASで画像のピクセルサイズと解像度の取得

NOTE記事一覧ですnote.com

【スクリプトエディタで開く】 |

swiftASで画像のピクセルサイズと解像度.scpt.scpt
ソース
001#!/usr/bin/env osascript
002#coding: utf-8
003----+----1----+----2----+----3----+----4----+----5----+----6----+----7--
004(*
005swiftを利用して
006画像のサイズを取得する変種
007画像のサイズの取得って意味では無意味だけど
008スクリプト内にswift使えるようになると、出来ることの幅が広がります
009
010
011com.cocolog-nifty.quicktimer.icefloe *)
012----+----1----+----2----+----3----+----4----+----5----+----6----+----7--
013use AppleScript version "2.8"
014use scripting additions
015
016#ダイアログ
017set listUTI to {"public.image"} as list
018try
019   tell application "SystemUIServer"
020      activate
021      set aliasFilePath to (choose file of type listUTI without multiple selections allowed) as alias
022   end tell
023on error strErrMes number numErrNo
024   log strErrMes & numErrNo
025   return false
026end try
027
028#UNIXパスに変換
029set strImageFilePath to (POSIX path of aliasFilePath) as text
030#SWIFTにパスを入れて
031set strSwiftCode to ("#!/usr/bin/env swift\n//coding: utf-8\nimport Foundation\nimport AppKit\nimport ImageIO\nlet strPath = \"" & strImageFilePath & "\"\nlet urlPath = URL(fileURLWithPath: strPath)\nguard let cgImageRead = CGImageSourceCreateWithURL(urlPath as CFURL, nil) else {exit(1)}\nguard let rawProperties = CGImageSourceCopyPropertiesAtIndex(cgImageRead, 0, nil), let dictProperties = rawProperties as? [String: Any] else {exit(1)}\nlet strWpx = dictProperties[kCGImagePropertyPixelWidth as String] ?? 0\nlet strHpx = dictProperties[kCGImagePropertyPixelHeight as String] ?? 0\nlet strWppi = dictProperties[kCGImagePropertyDPIWidth as String] ?? 72\nprint(\"\\(strWpx)\\t\\(strHpx)\\t\\(strWppi)\")") as text
032#実行する
033set strCmd to ("/bin/echo '" & strSwiftCode & "' | /usr/bin/swift - ")
034set strStdOut to (do shell script strCmd) as text
035
036#戻り値をタブ区切りにしたのでタブでリストにして
037set strDelim to AppleScript's text item delimiters
038set AppleScript's text item delimiters to tab
039set listImageSize to (every text item of strStdOut) as list
040set AppleScript's text item delimiters to strDelim
041#リストの順番であたいを取得する
042set strWpx to (first item of listImageSize) as text
043set strHpx to (second item of listImageSize) as text
044set strPPI to (last item of listImageSize) as text
045
046
047log strWpx as integer
048log strHpx as integer
049log strPPI as integer
AppleScriptで生成しました