Finderで選択した画像をImage Eventsを使って1920×1080サイズにクロップ(パディング)

Finderで選択した画像をImage Eventsを使って1920×1080または1080×1920サイズにクロップ、パディングを行うスクリプトです。
実行すると縦画像は縦に、横画像または正方形の画像は横に処理され、上書き保存となります。
余白は白色で、アルファチャンネルを含むものは透明状態でパディングされます。

-- http://www.macosxautomation.com/applescript/imageevents/07.html

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

property NSURLTypeIdentifierKey : a reference to current application's NSURLTypeIdentifierKey
property |NSURL| : a reference to current application's |NSURL|
property NSPredicate : a reference to current application's NSPredicate
property NSArray : a reference to current application's NSArray

tell application "Finder"
set aSel to the selection as alias list
end tell
if aSel = {} then return

set filRes to filterAliasListByUTI(aSel, "public.image") of me

tell application "Image Events"
repeat with i in filRes
using terms from application "Finder"
# https://enmtknt.hateblo.jp/entry/2022/03/01/145114
set hasAlpha to do shell script "sips -g hasAlpha " & quoted form of POSIX path of (contents of i) & " | grep 'hasAlpha' " & " | awk '{print $2}'"
end using terms from

# https://photocombine.net/padding/
if hasAlpha = "yes" then
set padColor to {65535, 65535, 65535, 0}
else
set padColor to {65535, 65535, 65535}
end if
set thisImage to open (contents of i)
set {aWidth, aHeight} to dimensions of thisImage
if (aWidthaHeight) then
--crop thisImage to dimensions {1920, 1080}
pad thisImage to dimensions {1920, 1080} with pad color padColor
else
--crop thisImage to dimensions {1080, 1920}
pad thisImage to dimensions {1080, 1920} with pad color padColor
end if
save thisImage
close thisImage
end repeat
end tell


########
--Alias listから指定UTIに含まれるものをエイリアスのリストで返す
on filterAliasListByUTI(aList, targUTI)
set newList to {}
repeat with i in aList
set j to POSIX path of i
set tmpUTI to my retUTIfromPath(j)
set utiRes to my filterUTIList({tmpUTI}, targUTI)
if utiRes is not equal to {} then
set the end of newList to j as POSIX file as alias
end if
end repeat
return newList
end filterAliasListByUTI

--指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
set aURL to |NSURL|'s fileURLWithPath:aPOSIXPath
set {theResult, theValue} to aURL's getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)

if theResult = true then
return theValue as string
else
return theResult
end if
end retUTIfromPath

--UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
set anArray to NSArray's arrayWithArray:aUTIList
set aPred to NSPredicate's predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
set bRes to (anArray's filteredArrayUsingPredicate:aPred) as list
return bRes
end filterUTIList
########

更新履歴

inserted by FC2 system