【メモ】AppleScript + Pixelmator Pro + ショートカット.app で3D変換用画像の下処理

Owl3Dに投げるための下処理用スクリプト。
Pillowで簡単に実装できるけどショートカットから使えたほうが便利だったので。

-- 縦横どちらかをフルHDに合わせるための比率計算
on mathNewSize(imageWidth, imageHeight)
	set widthRatio to 1920 / imageWidth
	set heightRatio to 1080 / imageHeight
	
	if widthRatio < heightRatio then
		set scaleFactor to widthRatio
	else
		set scaleFactor to heightRatio
	end if
	
	set newLayerWidth to imageWidth * scaleFactor
	set newLayerHeight to imageHeight * scaleFactor
	
	return {newLayerWidth, newLayerHeight}
end mathNewSize

-- 出力用ディレクトリ+ファイル名取得用
on getOutputPath(inputImagePath)
	set inputPOSIXPath to POSIX path of inputImagePath
	set {name:baseName, name extension:nameExtension} to (info for (POSIX file inputPOSIXPath))
	set baseName to text 1 thru ((length of baseName) - (length of nameExtension) - 1) of baseName
	set outputFileName to baseName & "_converted." & nameExtension
	set outputDir to POSIX path of (POSIX file (POSIX path of (inputImagePath as alias)))
	set outputPath to outputDir & outputFileName
	return outputPath
end getOutputPath

-- 黒背景のフルHD画像作成用
on createBackgroundWithImage(inputImagePath)
	tell application "Pixelmator Pro"
		-- 新しい1920x1080の黒背景画像を作成
		set backgroundImage to make new document with properties {width:1920, height:1080}
		tell backgroundImage
			fill layer 1 with color {0, 0, 0, 65535}
			
			set mainImageLayer to make new image layer with properties {file:inputImagePath, preserve transparency:true}
			
			-- image layerの幅と高さを取得
			set layerWidth to width of mainImageLayer
			set layerHeight to height of mainImageLayer
			
			set newSize to my mathNewSize(layerWidth, layerHeight)
			set width of mainImageLayer to item 1 of newSize
			set height of mainImageLayer to item 2 of newSize
			
			-- 中央揃えの位置を計算
			set newWidth to (1920 - (item 1 of newSize)) / 2
			set newHeight to (1080 - (item 2 of newSize)) / 2
			
			-- image layerを中央に配置
			set position of mainImageLayer to {newWidth, newHeight}
			set outputImagePath to my getOutputPath(inputImagePath)
			export backgroundImage to (outputImagePath) as PNG
			close backgroundImage without saving
		end tell
	end tell
end createBackgroundWithImage

on run {input, parameters}
	repeat with i in input
		set inputImagePath to alias i
		createBackgroundWithImage(inputImagePath)
		set outputImagePath to alias POSIX file getOutputPath(inputImagePath)
	end repeat
	
	tell application "Finder" to select item outputImagePath
end run


余談ですが動画で同じようなことをしようとする場合は以下のffmpegコマンドで可能

ffmpeg -i <入力先>  -vf "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2" -c:a copy <出力先>


この記事が気に入ったらサポートをしてみませんか?