Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: Image

Pixelmator Pro v2.4.1で新機能追加+AppleScriptコマンド追加

Posted on 4月 14, 2022 by Takaaki Naganoya

いまひとつ、「こういう表現を行いたいんだけど、どう操作していいのかわからない」感のあるPixelmator Pro。毎回、メニューを漁っては「これ、どう作るんだろうーなー」という手探り感があります。

Photoshopで育って、どっぷりPhotoshopで画像処理を理解した人がPixelmator Proを理解するのに、敷居の高さを感じます。これ、絶対に「こういう完成物を作りたい」という人向けに「こういう手順で操作すればいい」というマニュアル的なものが必要です。

さて、Pixelmator Proの新バージョンv2.4.1が登場。機械学習を利用した人物写真の自動切り抜き機能が目玉のようです。



Student with laptop photo created by freepic.diller – www.freepik.com

おお!まつげの箇所だけちょっと切れてしまったけど、これはいい感じ!



Lookstudio – jp.freepik.com によって作成された people 写真

上半身はほぼ完璧! こーれーはすごい。

いろんなスナップ写真を切り抜かせてみましたが、人物の全身が写っているとヒット率が高いようです。つまり、おかしな箇所を切り抜かれる危険性が低くなるということです。白いTシャツが抜ける危険性が高いようで、、、

Pixelmator 2.4.1 AppleScript用語辞書変更内容

export formatに「Motion」(Motion project.)が追加された
コマンド「select subject」追加。
コマンド「smart refine selection」追加。
コマンド「remove background」追加。
エレメント「color adjustments layer」「effects layer」追加。

クラス「image layer」がコマンド「remove background」と「decontaminate colors」に応答するようになった。
クラス「group laye」に要素「color adjustments layer」「effects layer」を追加
クラス「color adjustments layer」「effects layer」を追加

コマンド「draw elliptical selection」の同義語(draw oval selection)を廃止
コマンド「resize image」の同義語(adjust size、image size)を廃止
コマンド「resize canvas」の同義語(adjust canvas、canvas size)を廃止

冒頭の人物自動切り抜きを行うAppleScriptを書いてみると、こんな感じです。Pixelmator ProのAppleScript用語辞書にもサンプルScriptが掲載されています。

AppleScript名:人物自動切り抜き.scpt
tell application "Pixelmator Pro"
  tell front document
    remove background –v2.4.1 or later
  end tell
end tell

★Click Here to Open This Script 

Posted in Image | Tagged 10.15savvy 11.0savvy 12.0savvy Pixelmator Pro | Leave a comment

クリップボードの画像を指定色でモノクロ化してクリップボードへ v3

Posted on 3月 13, 2022 by Takaaki Naganoya

クリップボードに入れた画像を、グレースケール化したあとに指定の色のベタ塗り画像とフィルタで合成し、単色の色付き画像に変換するAppleScriptです。

資料に掲載する画像の情報量を減らすために、単色画像に変換したいと考えました。Photoshopだと2つのレイヤーの重ね合わせで指定して処理するような内容です。ただ、もうPhotoshopにできるぐらいのことの大部分は、AppleScriptだけで単独でできてしまうのが2022年的な状況です。

アプリケーションを使わずに処理するためには、CIFilterを用いて画像処理して、単色画像にすることになります。

CIFilterにもいろいろな画像フィルタ機能が用意されているわけで、ここから「どのフィルタを使うか」選ぶことになります。

# フィルタが200種類ぐらいあるんですけど!!

このような場合のために、FileMaker Proで作った「FileMaker Pro PowerPack」だとひととおりのCIFilterをサンプルデータで処理できるようにしておきました。

FileMaker Proのデータベース上にサンプルデータをコピー&ペーストしておけば、DB上でフィルタ処理してどのような処理をしてくれるかがわかります。

いやーー、作っておいてよかったー。「なんでこんなにフィルタ処理ばっかりあるんだよ!」的な話がありましたが、こうして実際に役立つわけで。フィルタの名称、編集できるテストデータ、処理結果が表示されるところまで……「動かせる資料」的なものに仕上がっています>FileMaker Pro PowerPack

ひととおりAppleScriptを作ってみて、いろいろ調整してみたところ……調整し切れなかったので、edama2さんに相談して(送りつけて)こんな感じに仕上がりました。

これでなんとか動くはずなのに、なぜこうなるのか。。。CIFilterを実際に日常的に使うツールで使ったのは実はこれが最初だったので、意外な挙動に割と困りました。


▲画面上の指定範囲のスクリーンショットを撮ってクリップボードへ


▲ScriptをmacOS標準搭載のスクリプトメニューから呼び出すことを前提に作った。


▲クリップボードの内容をペーストすると、単色化された画像が出力される

AppleScript名:クリップボードの画像を指定色でモノクロ化してクリップボードへ v3.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/03/11
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
–  v2 Takaaki Naganoya : マスクが1/4の大きさになったり2倍になったりしていた
–  v3 edama2:上記の問題に対処。クリーンナップ
—
use AppleScript version "2.7"
use framework "AppKit"
use framework "CoreImage"
use framework "Foundation"
use scripting additions

on run
  my main()
end run

on main()
  –クリップボード内のデータをNSImageとして取得
  
set sourceImg to my getClipboardASImage()
  
  
# 色指定
  
set aColor to my makeNSColorFromRGBA255val(252, 2, 128, 255)
  
  
  
# 同じ大きさの塗りつぶし画像を作成
  
tell current application’s NSImage’s alloc()
    tell initWithSize_(sourceImg’s |size|())
      lockFocus()
      
aColor’s |set|()
      
set aRect to current application’s NSMakeRect(0, 0, its |size|()’s width, its |size|()’s height)
      
current application’s NSBezierPath’s fillRect:aRect
      
unlockFocus()
      
set fillImg to it
    end tell
  end tell
  
  
# NSImage –> CIimage
  
set sourceImage to my convNSImageToCIimage(sourceImg)
  
set fillImage to my convNSImageToCIimage(fillImg)
  
  
set newImage to my filterImage2(fillImage, sourceImage)
  
  
my restoreClipboard({newImage})
end main

on filterImage2(fillImage, sourceImage)
  
  
set redValue to 0.295719844358
  
set greenValue to 0.295719844358
  
set blueValue to 0.295719844358
  
set alphaVlaue to 1.0
  
set aCIColor to current application’s CIColor’s alloc()’s initWithRed:redValue green:greenValue blue:blueValue alpha:alphaVlaue
  
  
tell current application’s CIFilter
    — CIFilter(モノクロ化)
    
tell filterWithName_("CIColorMonochrome")
      setDefaults()
      
setValue_forKey_(sourceImage, "inputImage")
      
setValue_forKey_(aCIColor, "inputColor")
      
set filteredImage to valueForKey_("outputImage")
    end tell
    
    
— CIFilter(モノクロ化)
    
tell filterWithName_("CIAdditionCompositing")
      setDefaults()
      
setValue_forKey_(fillImage, "inputImage")
      
setValue_forKey_(filteredImage, "inputBackgroundImage")
      
set theCIImage to valueForKey_(current application’s kCIOutputImageKey)
    end tell
  end tell
  
  
# CIImage –> NSImage
  
set imageRep to current application’s NSCIImageRep’s alloc()’s initWithCIImage:theCIImage
  
set rNSImage to current application’s NSImage’s alloc()’s initWithSize:(imageRep’s |size|())
  
rNSImage’s addRepresentation:imageRep
  
  
return rNSImage
end filterImage2

# NSImage –> CIimage
on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

— クリップボードの内容をNSImageとして取り出して返す
on getClipboardASImage()
  set thePasteboard to current application’s NSPasteboard’s generalPasteboard()
  
set theAttributedStringNSArray to thePasteboard’s readObjectsForClasses:({current application’s NSImage}) options:(missing value)
  
set theNSImage to theAttributedStringNSArray’s objectAtIndex:0
  
return theNSImage
end getClipboardASImage

on restoreClipboard(theArray as list)
  set thePasteboard to current application’s NSPasteboard’s generalPasteboard()
  
thePasteboard’s clearContents()
  
thePasteboard’s writeObjects:theArray
end restoreClipboard

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

★Click Here to Open This Script 

Posted in filter Image | Tagged 12.0savvy CIColor CIImage NSBezierPath NSCIImageRep NSColor NSImage NSPasteboard | Leave a comment

Intel MacとApple Silicon Macの速度差〜画像処理

Posted on 1月 2, 2022 by Takaaki Naganoya

macOS 11から12に移行して、なぜかリリースが近づくにつれて細かいバグや巨大なバグが顕在化し、まだ手放しでおすすめできる状況にないのが心苦しいところですが、AppleScriptからのCocoa呼び出しについてはIntel Mac/Apple Silicon Macでも速度が向上。とくに、Apple Silicon Macでの速度向上が顕著です。

で、特定の処理(巨大なlistやrecord in list同士の検索)でM1 Mac miniがiMac Proの2.5倍ぐらい速いといったベンチマークは出しているわけですが、いかにもApple Silicon Macで処理が速そうな画像処理のベンチマークを実施してみました。

Intel Mac mini 2014が手元からなくなってしまったので、以前のメインマシンであったMacBook Pro Retina 2012(MacBookPro10,1)と比較してみました。

ベンチマーク内容は、指定の画像が空白かどうかをチェックするというものです。フルHD画像でも4K画像でも8K画像でも、1ピクセルでも白くない点があれば検出できるという処理内容。外部のGPUImage FrameworkやPhotoshopのヒストグラム処理を呼び出すよりもAppleScriptだけで処理した方が速いというものです(8K画像だとPhotoshopの方が速いかも)。


▲画像解像度の変化と処理時間の相関。グラフは数値が小さいほど高速。巨大な画像になると処理速度差が大きくなる傾向にある?

だいたい、MacBook Pro Retina 2012と比べて3〜4倍ぐらいM1 Mac miniの方が高速です。MacBook Pro Retina 2012は2017年のMacBook Pro 13インチといい勝負ぐらいの速度が出ており、古い割にはごく最近まで使えていました。

そこから3〜4倍高速ということで、M1 Mac miniはコストの割にはパワフルです。ファンレスのMacBook Air M1でも同程度の速度が出るはずです。

一方で、M1 Pro/M1 Max搭載のMacBook ProでM1機よりも大幅に高速なのかと言われると……このぐらいの静止画の処理程度だとごくわずかな差しかつかないはずです。下手をすると、速度差がないかもしれません。

→ Download blank_image_detection_benchmark.zip (including script libraries)

–> Download test Data


▲バーが短いほど高速。M1がM1 Maxの2倍高速という結果が出てしまった。M1 Max MBPは2014年のIntel Mac miniより少し速いだけのマシンという結果に。2018年のIntel Mac miniとの比較だとM1 Max MBPよりもIntel Mac miniのほうが速そう

M1、M1 Max、M1 Ultra(最上位機種)で処理時間を比較した結果。予想どおりM1がM1 MaxやM1 Ultraよりも2倍以上高速。もはや8K画像ぐらいは、大きなデータにならないというべきなのか。

AppleScript名:画像の空白判定 v4_bench_時間計測.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/01
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7"
use framework "Foundation"
use framework "AppKit"
use scripting additions
use mdLib : script "Metadata Lib" version "2.0.0"
use easyTable : script "display table by list"

set aFol to choose folder

set aResList to perform search in folders {aFol} predicate string "kMDItemContentTypeTree CONTAINS %@" search arguments {"public.image"}

set aList to {}
repeat with i in aResList
  set a1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
  
  
set iRes to checkImageIsWhite(i) of blankImageKit of me
  
  
set b1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
  
set c1Dat to b1Dat – a1Dat
  
  
set aName to (current application’s NSString’s stringWithString:i)’s lastPathComponent() as string
  
  
if iRes = true then
    set jRes to "White"
  else
    set jRes to "Black"
  end if
  
  
–log {aName, jRes}
  
  
set the end of aList to {aName, jRes, c1Dat}
end repeat

set fLabels to {"File name", "Result", "Estimate(Seconds)"}
set aRes to (display table by list aList main message "Blank Image check" size {800, 600} labels fLabels)
return aList

script blankImageKit
  use AppleScript version "2.7" — High Sierra (10.13) or later
  
use framework "Foundation"
  
use framework "AppKit"
  
use scripting additions
  
property parent : AppleScript
  
  
property NSData : a reference to current application’s NSData
  
property |NSURL| : a reference to current application’s |NSURL|
  
property NSColor : a reference to current application’s NSColor
  
property NSImage : a reference to current application’s NSImage
  
property NSBezierPath : a reference to current application’s NSBezierPath
  
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
  
  
  
–Compare Original Data and
  
on checkImageIsWhite(aFile)
    set aPOSIXpath to POSIX path of aFile
    
set aURL to |NSURL|’s fileURLWithPath:(aPOSIXpath)
    
    
set aNSImage to NSImage’s alloc()’s initWithContentsOfURL:(aURL)
    
set bNSImage to NSImage’s alloc()’s initWithContentsOfURL:(aURL)
    
    
set fillColor1 to NSColor’s clearColor()
    
set blankNSImage1 to drawImageWithFilledColor(aNSImage, fillColor1) of me
    
    
set fillColor2 to makeNSColorFromRGBAval(65535, 65535, 65535, 65535, 65535) of me –white
    
set blankNSImage2 to drawImageWithFilledColor(bNSImage, fillColor2) of me
    
    
set aTiff to blankNSImage1’s TIFFRepresentation()
    
set bTiff to blankNSImage2’s TIFFRepresentation()
    
    
set chkWhite to (aTiff’s isEqualToData:bTiff) as boolean
    
    
return chkWhite
  end checkImageIsWhite
  
  
  
on getSizeOfImage(anNSImage)
    set aSize to anNSImage’s |size|()
    
set aClass to class of aSize
    
if aClass = record then
      copy aSize to theSize –To macOS 10.12.x
    else –macOS 10.13 or later
      set sizeX to (item 1 of item 2 of aSize)
      
set sizeY to (item 2 of item 2 of aSize)
      
set theSize to {width:sizeX, height:sizeY}
    end if
    
return theSize
  end getSizeOfImage
  
  
  
–指定サイズの画像を作成し、背景を指定色で塗る
  
on drawImageWithFilledColor(anImage, fillColor)
    set aSize to getSizeOfImage(anImage) of me
    
    
anImage’s lockFocus()
    
    
set theRect to {{x:0, y:0}, {width:(width of aSize), height:(height of aSize)}}
    
set theNSBezierPath to NSBezierPath’s bezierPath
    
theNSBezierPath’s appendBezierPathWithRect:theRect
    
fillColor’s |set|()
    
theNSBezierPath’s fill()
    
    
anImage’s unlockFocus()
    
    
return anImage
  end drawImageWithFilledColor
  
  
  
–aMaxValを最大値とする数値でNSColorを作成して返す
  
on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
    set aRedCocoa to (redValue / aMaxVal) as real
    
set aGreenCocoa to (greenValue / aMaxVal) as real
    
set aBlueCocoa to (blueValue / aMaxVal) as real
    
set aAlphaCocoa to (alphaValue / aMaxVal) as real
    
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
    
return aColor
  end makeNSColorFromRGBAval
  
end script

★Click Here to Open This Script 

Posted in Image | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy NSBezierPath NSBitmapImageRep NSColor NSData NSDate NSImage NSURL | Leave a comment

Pixelmator Proで指定の画像を複数の3D LUTを用いてカラー調整して画像書き出し

Posted on 5月 2, 2021 by Takaaki Naganoya

Pixelmator Pro v2.0.8で追加された3D LUT(Look Up Table)によるカラー調整機能。これを用いて、複数の3D LUTファイルによるカラー調整を行い、それぞれ3D LUTファイルのファイル名を反映させて書き出すAppleScriptです。

3D LUTファイルは、探してみるとあちこちで配布されており、割とありふれた存在のようです。実際にフリー配布されている3D LUTファイルをダウンロードしてきて、1つのフォルダに入れておき、指定画像に対してカラー調整を行わせてみました。

–> [全てフリー!] シネマティックなルックになる10のLUTsを紹介します!!

フォルダに入っている3D LUTファイルをすべてループで処理するので、3D LUTファイル100個でも1,000個でも処理できますし、ちょっと書き換えれば複数の画像に対してそれぞれすべての3D LUTファイルによる色調整を実行するようにもできます。

AppleScript名:指定の画像を複数の3D LUTでカラー調整して画像書き出し.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/02
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

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

–処理対象の画像を選択
set anImage to choose file of type {"public.image"} default location (path to pictures folder) with prompt "Select Proc Image"
set imgParent to getParentPathFromAlias(anImage) of me

–3D LUTファイルを入れてあるフォルダを選択
set lutFolder to choose folder with prompt "Select 3D LUT folder"

–Filter 3D LUT (.cube) files only
tell application "Finder"
  set fList to (every file of folder lutFolder) as alias list
end tell

set lutList to getFilesWithUTI("com.blackmagicdesign.cube", fList) of me

–指定の画像ファイルをオープン
tell application "Pixelmator Pro"
  close every document saving no
  
open anImage
end tell

–Main Loop
repeat with i in lutList
  set aLut to contents of i
  
  
–ファイルパスの加工処理
  
set newImgName to ((current application’s NSString’s stringWithString:(POSIX path of aLut))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".jpg") as string
  
set newImgFullPath to (imgParent as string) & "/" & newImgName
  
set newImgFile to POSIX file newImgFullPath
  
  
tell application "Pixelmator Pro"
    activate
    
tell front document
      tell color adjustments of first layer –ここだけ、ネスティングを分割するとエラーになる
        set its custom lut to aLut
      end tell
      
      
export to newImgFullPath as JPEG with properties {compression factor:0.5, bits per channel:8}
      
undo
    end tell
  end tell
end repeat

–後片付け
tell application "Pixelmator Pro"
  tell front document
    close without saving
  end tell
end tell

on getParentPathFromAlias(aliasPath)
  set aPath to POSIX path of aliasPath
  
set pathString to current application’s NSString’s stringWithString:aPath
  
set newPath to pathString’s stringByDeletingLastPathComponent()
  
return newPath
end getParentPathFromAlias

on getFilesWithUTI(acceptUTI, aliasList)
  set aList to {}
  
  
repeat with i in aliasList
    set anAlias to i as alias
    
set aUTI to getUTIfromPath(anAlias) of me
    
if aUTI is not equal to missing value then
      set uRes to filterUTIList({aUTI}, acceptUTI) of me
      
      
if uRes is not equal to {} then
        set the end of aList to contents of i
      end if
    end if
  end repeat
  
  
return aList
end getFilesWithUTI

–AliasからUTIを求める
on getUTIfromPath(anAlias)
  set aPOSIXpath to POSIX path of anAlias
  
set aURL to current application’s |NSURL|’s fileURLWithPath:aPOSIXpath
  
if aURL = missing value then return missing value
  
set aRes to aURL’s resourceValuesForKeys:{current application’s NSURLTypeIdentifierKey} |error|:(missing value)
  
if aRes = missing value then return missing value
  
return (aRes’s NSURLTypeIdentifierKey) as string
end getUTIfromPath

–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

★Click Here to Open This Script 

Posted in Color file File path Image | Tagged 10.14savvy 10.15savvy 11.0savvy Pixelmator Pro | Leave a comment

Pixelmator Pro がv2.0.8で3D LUTをサポート

Posted on 5月 2, 2021 by Takaaki Naganoya

Pixelmator Proがv2.0.5からv2.0.8にバージョンアップして、3D LUT(Look Up Table)をサポートしました。

自分は知らなかったのですが、映像や画像の処理時に、色の明度カーブをテーブルで置き換えることで、色の調子を整えたり、「●●っぽい色(光)使い」のデータを他の映像/画像データに統一的に適用させたりと、カラーフィルタ的なものをプログラムではなくデータで表現したもの、と理解しました。カラーコレクション系の技術というか手法で、調べてみるとnVidiaとかAdobeとか、そういう会社が関わってきたようで。

3D LUTのファイル(拡張子「.cube」)のUTIを確認したところ、”com.blackmagicdesign.cube”。ビデオ編集関連のハードウェア/ソフトウェアでさまざまな製品を世に送り出しているBlackMagic Designが仕様の策定を行っているのでしょうか。

この3D LUTをPixelmator Proがサポート。42個のLUTをアプリケーション内で持っているほか、外部の3D LUTファイルを指定することも、Pixelmator書類から3D LUTを生成して書き出すこともできるようです。

AppleScript用語辞書的には、「export as lut」コマンドを新設したことと、「color adjustments」コマンドに「custom lut」を指定するオプションを追加しています。

AppleScript名:現在オープン中の写真に指定のLUTを反映させる.scpt
–Pixelmator Pro用語辞書内に掲載されているサンプルを、読みやすいように書き換えた
set lutFile to choose file with prompt "Choose the LUT you’d like to apply to the layer:" of type {"com.blackmagicdesign.cube"}

tell application "Pixelmator Pro"
  tell front document
    tell color adjustments of first layer –ここだけ、ネスティングを分割するとエラーになる
      set its custom lut to lutFile
    end tell
  end tell
end tell

★Click Here to Open This Script 

Githubを調べてみたら、Objective-Cで書かれた「CocoaLUT」というプロジェクトを見つけました。ずいぶん前から(7年以上前から)存在していたようで、自分は寡聞にしてこれを知りませんでした。ひととおり機能に目を通してみると、3D LUTのファイルを読み込んでNSImageにカラー変更を適用するといった処理が行えるようです。AppleScriptからダイレクトにCocoaLUTを呼び出して色変更できそうです。

一応、Pixelmator Proの「謝辞」を見てみたところ、「CocoaLUT」に関する記載はなかったので、Pixelmator Proでこのプロジェクトの成果物を利用しているといったことはなさそうです。

YouTubeにアップしたムービーをご覧いただければわかるように、Pixelmator Proで3D LUTによる色置換処理を行ってみると、とても高速です。

Posted in Color Image | Tagged 10.14savvy 10.15savvy 11.0savvy Pixelmator Pro | Leave a comment

画面スナップショット超解像バッチ処理 v1

Posted on 3月 25, 2021 by Takaaki Naganoya

Pixelmator Proの機能「ML Super Resolution」をAppleScriptから呼び出して、指定フォルダ内の画像をすべて超解像処理を行って、機械学習モデルをもとに解像度2倍化を行った画像を別フォルダに書き出すAppleScriptです。

超解像処理を行う対象は、別に画面のスナップショット画像でなくてもよいのですが、効果がわかりやすい用途です。

Keynoteに画面スナップショット画像を貼り付けていたときに、拡大倍率が上がると解像度が足りずに荒くなってしまいました。Retina環境で画面のスナップショットを取ると、けっこう綺麗に拡大できるのですが、等倍表示しかできない(&画面表示解像度を落とすことで2x Retina解像度で画面キャプチャ可能)環境なので、ちょっと困りました。


▲macOS 11.0、見た目の悪さで使う気が失せるはじめてのmacOS。12.0ではもう少しなんとかしてほしい。とくに、このダイアログ。ダイアログと見分けのつかないウィンドウ。ファイル保存ダイアログとかも

そこで、Pixelmator Proで画像のML Super Resolution機能(超解像機能)を用いてソフトウェアの力で画面スナップショット画像を高解像度化してみました。これが予想を超えていい感じだったので、指定フォルダ以下の画像をすべて処理するようにAppleScriptで処理してみました。

–> Download pixelmatorMLSuperResol(Script Bundle with libraries)

ML Super Resolution処理は自分の使っているIntel Mac(MacBook Pro 10,1)には荷の重い処理でささいな画像でも数秒かかりますが、おそらくApple Silicon搭載Macだと瞬殺でしょう。Core MLの処理が段違いに速いので。


▲オリジナル画像(左)、超解像処理を行なった画像(右)


▲オリジナル画像と超解像処理を行なった画像のファイルサイズの違い

本リストは実際にAppleScriptで開発を行う際に記述するコード量そのものを示したものです。本リストには2つのライブラリを利用していますが、ふだんはプログラムリストの再現性(実行できること)を優先して、ライブラリ部分もScript本体に一緒に展開しています。使い回ししている分も同じリストに展開しているので、「たくさん書かないといけない」と思われているようです。

実際には、共通部分はほとんど書いていないので、本処理もこんな(↓)ぐらいの記述量です。リアルな記述量を感じられるような掲載の仕方を考えなくてはいけないのかもしれません。本リストはその試みの第一歩です。

まー、超解像処理を行って72dpiの画面スナップショット画像を144dpiに上げているだけなんで、Retina Display環境で処理すれば不要なんですが、ソフトウェアだけで実現できるのはロマンを感じますし、無駄に2x Retina環境のスクリーンショットを処理して288dpiの高解像度画像に上げてみるとか。

ただ、WWDCのビデオなどを見ていると、画面のスナップショットそのものをベクターグラフィックで取るような仕組みも考えていそうな気配がします。当てずっぽうですが、そういう何かを考えていそうな….

AppleScript名:画面スナップショット超解像バッチ処理 v1
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/03/25
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use cPathLib : script "choosePathLib"
use imgPicker : script "imgPickerLib"

–掃除
tell application "Pixelmator Pro" to close every document without saving

–必要なパス情報をユーザーに問い合わせる
set {inFol, outFol} to choose multiple path with titles {"Img Folder", "Output Folder"}
set outFolStr to outFol as string

–画像フォルダから画像のパス一覧を取得
set f1List to getFilepathListByUTI(POSIX path of inFol, "public.image", "alias") of imgPicker

–取得した画像を超解像処理して
repeat with i in f1List
  tell application "Pixelmator Pro"
    open i
    
tell front document
      with timeout of 3000 seconds
        super resolution
      end timeout
    end tell
  end tell
  
  
–新規保存ファイルパスの作成
  
set pathStr to POSIX path of i
  
set filenameStr to (current application’s NSString’s stringWithString:(pathStr))’s lastPathComponent() as string
  
set savePath to outFolStr & filenameStr
  
  
tell application "Pixelmator Pro"
    save front document in file savePath as PNG
    
    
tell front document
      close without saving
    end tell
  end tell
end repeat

★Click Here to Open This Script 

Posted in file File path Image UTI | Tagged 10.14savvy 10.15savvy 11.0savvy Pixelmator Pro | Leave a comment

Pixelmator ProのSVG to PNG変換

Posted on 12月 28, 2020 by Takaaki Naganoya

Pixelmator ProでSVGのファイルをPNG形式で書き出すAppleScriptです。

この、ダイアログでファイルを選択して書き出しファイル名を入力させるタイプのAppleScriptをたくさん掲載していますが、もともとAppleScriptの一括処理的なプログラムで、いちいちダイアログを出して1つ1つのファイルを保存させるようなことはやりません。あくまで、サンプルScriptの動作を完結させるための仕様です。

実際には、指定フォルダ以下にあるSVGファイルをSpotlightで抽出して、まとめて書き出し先のフォルダにPNG形式で書き出すといった処理になるでしょう。

SVG方面では1024jpさんのGapplinがあり、こちらもAppleScript対応しており各種操作が行えるようになっているのですが、Sandbox対応度に問題があるためかファイル書き出し操作がAppleScriptから行えていないので、現状では大量のSVG書類の変換にはPhotoshopかPixelmator Proということになりそうです。

SVGを読み込んで他の画像形式に書き出すためのCocoa Frameworkを利用できるとよさそうですが、いまひとつうまく動くものを知りません。


▲SVG対応のアプリケーション。SVGを読めるもの、書けるもの、書き出せるもの、と対応度はさまざま

AppleScript名:PixelmatorのSVG to PNG変換
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/12/01
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.7" — Yosemite (10.13) or later
use framework "Foundation"
use scripting additions

set aFile to choose file of type {"public.svg-image"}
set outPath to choose file name with prompt "select output file name"

tell application "Pixelmator Pro"
  open aFile
  
  
tell front document
    export to outPath as PNG
    
close without saving
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:GaplinのSVG to PNG変換
set aFile to choose file of type {"public.svg-image"}
set outPath to choose file name with prompt "select output file name"

tell application "Gapplin"
  open aFile
  
  
tell front document
    export to outPath as PNG with options {class:export options, scale:1.0}
    
close without saving
  end tell
end tell

★Click Here to Open This Script 

Posted in file Image | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Pixelmator Pro | Leave a comment

FileMaker ProのObject FieldにNSImageを設定する

Posted on 12月 26, 2020 by Takaaki Naganoya

FileMaker Proデータベースのオブジェクトフィールド上に生成したNSImageを入れるAppleScriptです。FileMaker Pro v19.2.1.14+macOS 11.2betaで動作確認しています。とくに環境依存は行わないはずです。

FileMaker Proのオブジェクトフィールドは一種のBlobで、画像やPDF、機械学習モデル(mlmodel)、他のデータベース(.fmp12)を突っ込んだりできます。

ところが、AppleScriptでNSImageを作成し、その結果をFileMaker Proのオブジェクトフィールドにそのまま入れることはできません。エラーになります。

方法1:AppleScript側でNSImageをクリップボードに入れ、FileMaker Pro側でクリップボードの内容をフィールドに入れる

この方法は、FileMaker Pro側が最前面にある場合には問題なかったのですが、FileMaker Proが最前面にない場合には問題が発生する可能性があります。実際に試して成功したのですが、クリップボード経由でAppleScript側とFileMaker Script側がデータをやりとりすることになり、膨大なデータを処理した場合の信頼性に疑問がつきました。

方法2:AppleScript側でNSImageをクリップボードに入れ、クリップボードの内容を標準命令で画像に変換したのち、普通にオブジェクトフィールドに入れる

各種アプリケーションが認識する「画像データ」に明示的に変換するためには、ファイルに書き出すのが確実ですが、クリップボード経由で「画像」に変換するのが安全策です。

NSImageをJPEGデータに変換して、その結果をそのままオブジェクトフィールドに突っ込んでもエラーになりました。これが最有力な案だと思っていたので、うまく動かなかったのは残念でした。

そこで、安全策をとって(仕方なく)クリップボード経由でNSImageを画像に変換することになりました。このままでは方法1と大差ないように見えますが、実際にはAppleScriptでクリップボードにNSImageを入れて、AppleScriptでクリップボード内容を画像として評価して取得するという処理を行っています。

スピードや確実さを考慮すると、なるべくクリップボード経由の処理は行いたくないので、対策は考えておきたいところです。クリップボードや一時ファイルを経由させるよりも、極力メモリ上で対処したいところです。


▲ユーザーにAppleScriptの実行権限を与えておくとAppleScriptによる制御が有効になるFileMaker Pro


▲テキストフィールド「originalString」から文字情報を取り出して、オブジェクトフィールド「imageStore」にAppleScriptで生成した画像を突っ込む


▲実行前


▲実行後(Mac mini 2014で処理に初回で0.1秒ほど。2回目以降は1桁速くなる) AppleScript側で画像を作成してフィルタ処理をかけたりして、好き放題に合成してFileMaker DB上のフィールドに設定できる。バーコードやQRコードをAppleScript側で生成して設定したり、PDFをレンダリングした画像を設定できるのは便利

AppleScript名:NSImage to FM Object Field v2.scptd
— Created 2020-12-20 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property fmBundleID : ""

set fmBundleID to getBundleID() of me

–DB側から画像化するテキストを取得する
using terms from application "FileMaker Pro"
  tell application ID fmBundleID
    tell window 1
      tell current record
        set aText to field "originalString"
      end tell
    end tell
  end tell
end using terms from

set aWidth to 500.0 –幅
set aHeight to 200.0 –高さ

set fillColor to current application’s NSColor’s blackColor –塗り色
set drawColor to current application’s NSColor’s whiteColor –文字色

set {xPos, yPos} to {1, 5}

–新規画像を作成して背景を塗る
set aImage1 to makeImageWithFilledColor(aWidth, aHeight, fillColor) of me

–画像に文字を塗る
set aImage2 to drawStringsOnImage(aImage1, aText, "HiraKakuStd-W8", 36.0, drawColor, xPos, yPos) of me

(my restoreClipboard:{aImage2})
using terms from scripting additions
  set tmpImg to the clipboard as JPEG picture
end using terms from

–DBに画像を設定する
using terms from application "FileMaker Pro"
  tell application ID fmBundleID
    tell window 1
      tell current record
        set field "imageStore" to tmpImg
      end tell
    end tell
  end tell
end using terms from

–画像のうえに指定の文字を描画して画像を返す
on drawStringsOnImage(anImage, aText, aFontName, aPoint, drawColor, xPos, yPos)
  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}
  
  
–文字描画開始
  
anImage’s lockFocus()
  
aString’s drawAtPoint:(current application’s NSMakePoint(xPos, yPos)) withAttributes:aDict
  
anImage’s unlockFocus()
  
–文字描画ここまで
  
  
return anImage
end drawStringsOnImage

–指定サイズの画像を作成し、背景を指定色で塗る
on makeImageWithFilledColor(aWidth, aHeight, fillColor)
  –Imageの作成  
  
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

on getBundleID()
  –FileMaker Pro 18
  
set fmProID to "com.filemaker.client.pro12"
  
  
–FileMaker Pro 18 Advanced
  
set fmProADVID to "com.filemaker.client.advanced12"
  
  
using terms from application "FileMaker Pro"
    tell current application
      set aName to name
    end tell
  end using terms from
  
  
if aName contains "Advanced" then
    return fmProADVID
  else
    return fmProID
  end if
end getBundleID

–クリップボードに内容を設定する
on restoreClipboard:theArray
  — get pasteboard
  
set thePasteboard to current application’s NSPasteboard’s generalPasteboard()
  
  
— clear it, then write new contents
  
thePasteboard’s clearContents()
  
thePasteboard’s writeObjects:theArray
end restoreClipboard:

★Click Here to Open This Script 

Posted in Image | Tagged 10.14savvy 10.15savvy 11.0savvy FileMaker | Leave a comment

Pixelmator Proでアイコン書き出しv2

Posted on 10月 19, 2020 by Takaaki Naganoya

Pixelmator Proで1024×1024 pixelの画像をmacOSのアプリケーションアイコン素材用に各サイズにリサイズして連続書き出しするAppleScriptです。

Pixelmator ProのAppleScriptプログラミングコンテスト優勝賞品Pixelmator Pro。非破壊画像処理を行い、GPUベースの高速な処理を行うPixelmator Proを実務的な画像処理に使うとどんな感じなのか、いろいろ調べていたらアイコン書き出し用の複数同時解像度書き出し機能などはついていなかったので、さくっと作ってみました。

Photoshopを操作して各種解像度書き出しを行うよりも高速に感じます(厳密にベンチマークを計測したわけではないんですけれども)。

AppleScript名:Pixelmator Proでアイコン書き出しv2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/19
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

set resolList to {1024, 512, 256, 128, 64, 32, 16}
set aTargFileBase to (choose file name with prompt "Select Export base name") as string

tell application "Pixelmator Pro"
  if (exists of document 1) = false then
    display dialog "There is no document" buttons {"OK"} default button 1 with icon 1
    
return
  end if
  
  
tell the front document
    set aWidth to width
    
set aHeight to height
    
    
if {aWidth, aHeight} is not equal to {1024.0, 1024.0} then
      display dialog "Wrong Image Size (1024×1024 required)" buttons {"OK"} default button 1 with icon 2 with title "Size Error"
      
return
    end if
    
    
repeat with i in resolList
      resize image width i height i resolution 72 algorithm bilinear
      
export to file (aTargFileBase & "_" & (i as string) & "x" & (i as string) & ".png") as PNG
      
undo
    end repeat
  end tell
end tell

★Click Here to Open This Script 

Posted in file Image | Tagged 10.14savvy 10.15savvy 11.0savvy Pixelmator Pro | 1 Comment

SFPSDWriterのじっけん v2

Posted on 9月 21, 2020 by Takaaki Naganoya

AppleScriptからPhotoshopのデータ(PSD)を出力するテストプログラムです。

AppleScriptにはPhotoshopのデータを書き出す関数や機能はとくに用意されていないため、Photoshopのデータを書くためにはPhotoshopにコマンドを送って実行してもらうのが定番です。

この定番の方法だと、Photoshopが存在しない環境でPhotoshopのデータを作ることができません。この問題を解決するためにはオープンソースで公開されている「Photoshopデータを書くプログラム部品」を呼び出すことになります。

Photoshopデータについては一定の需要があるためか、AdobeがPhotoshopデータ形式の詳細な資料を公開しているためか、Reader(読むプログラム)とWriter(書くプログラム)の2通りのプログラムが存在します。

■PSD Reader/Parser
PSD-Font-Reader
psdparse

■PSD Writer
FMPSD
PSDWriter
SFPSDWriter

ここでは、「SFPSDWriter」内に含まれる「SFPSDWriter」Frameworkを呼び出しています。

–> Download SFPSDWriter.framework(To ~/Library/Frameworks)

実行にあたっては、macOS 10.14以降ではScript Debuggerを用いるか、お使いのMacをSIP解除してScript Editor上で呼び出して実行する必要があります。

ちょっと書き換えるとXcode上でも呼び出せることでしょう。Mac App Storeに出すAppleScript Cocoaアプリケーション(Sandbox対応)内で利用する場合には、ファイル書き込みパスをユーザーに明示的に選択させる必要があるため、choose file nameダイアログでファイル名を入力・選択してもらうようにすべきです(デフォルト指定のファイル名をUUIDで自動生成するとか)。

本AppleScriptはKamenokoから書き出せるデータを増やすべく「Photoshop形式のデータを書けたらどうだろう?」と実験してみた残骸です。結局、PDFで書き出せるしPDFなら拡大縮小しても荒くなったりしないので、PDFのほうがいいという結論に。

Pixelmator Proのデータ形式とかPSD形式で書き出す実験は行っているのですが、処理結果を見るとどちらも「PDF形式のほうがいい」という結論に至っています。


▲ベクターデータではないので、拡大するとアラが見える

AppleScript名:SFPSDWriterのじっけん v2
— Created 2016-03-12 by Takaaki Naganoya
— Modified 2019-02-27 by Takaaki Naganoya
— Modified 2020–09-21 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "SFPSDWriter" –https://github.com/shinyfrog/SFPSDWriter

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSUUID : a reference to current application’s NSUUID
property NSImage : a reference to current application’s NSImage
property SFPSDWriter : a reference to current application’s SFPSDWriter
property NSWorkspace : a reference to current application’s NSWorkspace

property SFPSDResolutionUnitPPI : 1
property SFPSDResolutionUnitPPC : 2

set anWriter to (SFPSDWriter’s alloc()’s initWithDocumentSize:(current application’s CGSizeMake(1200, 400)) andResolution:72.0 andResolutionUnit:(SFPSDResolutionUnitPPI))

set aCount to 1

repeat with yPos from 0 to 400 by 110
  repeat with xPos from 0 to 1024 by 110
    set aImage to (current application’s NSImage’s alloc()’s initWithSize:{100, 100})
    
set aColor to current application’s NSColor’s redColor()
    
my drawCircleOnNSIMage(aImage, 100, 0, 0, aColor)
    
    (
anWriter’s addLayerWithNSImage:aImage andName:("Layer_" & aCount as string) andOpacity:1.0 andOffset:{x:(xPos as real), y:(yPos as real)})
    
set aCount to aCount + 1
  end repeat
end repeat

set aPSD to anWriter’s createPSDData()

set theName to NSUUID’s UUID()’s UUIDString()
set pathString to NSString’s stringWithString:("~/Desktop/output_" & theName & ".psd")
set newPath to pathString’s stringByExpandingTildeInPath()

aPSD’s writeToFile:newPath atomically:true

#  MARK: Call By Reference
on drawCircleOnNSIMage(aImage, aRadius, aXpos, aYpos, aColor)
  set aBezier to generateCircle(aRadius, aXpos, aYpos) of me
  (
aImage)’s lockFocus()
  
aColor’s |set|()
  
aBezier’s fill() –ぬりつぶし
  (
aImage)’s unlockFocus()
end drawCircleOnNSIMage

#  MARK: circleのBezier曲線を作成して返す
on generateCircle(theRadius, x, y)
  set aRect to current application’s NSMakeRect(x, y, theRadius, theRadius)
  
set aCirCle to current application’s NSBezierPath’s bezierPath()
  
aCirCle’s appendBezierPathWithOvalInRect:aRect
  
return aCirCle
end generateCircle

★Click Here to Open This Script 

Posted in file Image | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Photoshop | Leave a comment

画像の空白判定プログラムの検証

Posted on 7月 28, 2020 by Takaaki Naganoya

画像の全ピクセルが白かどうかチェックする処理ルーチンは、必要に迫られて作ったものです。しかも、高速処理が求められます。

アイコン画像よりも小さな、たかだか1024 x 768ピクセルの画像であっても、全画素の空白をループでチェックしたら78万ピクセルあるわけで、地道に画像に対して座標を指定しつつ78万回カラーチェックを行うのは現実的ではありません。

作成した空白チェックのルーチンは3つ。

(1)Photoshopの明度ヒストグラム機能を利用するもの

Adobe Photoshopの明度ヒストグラム機能を利用するもの。はるかかなた昔から使っており、信頼性も高かったものの実行にはPhotoshopを要するため、どこでも同様に実行するわけにはいきませんでした。HTMLをPDF出力させたときに、無駄な空白ページが末尾にできることをチェックしたりと、重要な処理に使ってきました(プリントアウト時に無駄紙を省けるとか。枚数が増えると割と切実な問題です)。

(2)GPUImage.frameworkを利用するもの

オープンソースのGPUImage.framework(Objective-Cで書かれた初代のGPUImage 1)を呼び出して明度ヒストグラム計算を実行。スピード、コストなどの面で問題を解決できていますが、GPUImage自体がSwiftで書き直されたり、OpenGLからMetal向けに書き直されたりで、GPUImage 1自体の継続性については問題がある状態です。

(3)AppleScriptだけで書き直したもの

Cocoaの機能を利用して画像の空白チェックを実現。元画像のコピーを作って、白くぬりつぶして、オリジナル画像との照合を行う。同じであれば空白画像、同じでなければ空白画像ではないという判定を行います。4K解像度以下であれば最速。

そして、今後(1)〜(3)のどれを使い続けるべきかを、macOS 10.14.6でチェックしてみました。テストプログラムでは空白画像検出時にtrueを、空白でない場合にはfalseを返す仕様に。

(1) (2) (3)
1024x768_1_black.png false true false
4K_3840x2160_1_pixel_black.psd false true false
1x1_white.png true false true

結果は、(1)と(3)が同じ結果を返しました。(2)だけ結果が異なるケースが見られたため、Photoshopの有無に左右されないことを考えると(3)が有力といえます。

実際に、Mac App Store上で販売しているPDF差分検出ツール「Double PDF」ではv2.0からはGPUImageの利用をやめ、処理内容をすべてAppleScriptだけで行うことでスピードアップを果たしています。

この空白画像の検出以外でどの程度GPUImage 1がmacOS 10.14以降の環境で使えるか、使えないかは別のテストが必要でしょう。

Posted in Image | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Photoshop | Leave a comment

Keynote書類上の画像を実パスを求めてアーカイブ展開してオープン

Posted on 7月 4, 2020 by Takaaki Naganoya

Keynote書類上の指定画像のアーカイブ中のパスを求め、指定画像のファイル名と照合し、当該画像ファイルのみアーカイブ展開してからPreview.appでオープンするAppleScriptです。

Keynote書類には2つの形式(パッケージ形式、フラット形式)があり、現在のデフォルトはフラット形式です。

パッケージ形式についてはFinder上でパッケージバンドルを表示させて、内部データ構造を実際に見られるようになっています。

では、フラット形式はどうかといえば、上記のパッケージ形式データをZip圧縮して拡張子を「.key」に変更したものです。

そのため、拡張子を「.key」から「.zip」に付け替えて、アーカイブ展開すると、実際にパッケージ内部のファイルにアクセスできます。

本Scriptは、フラット形式のKeynote書類に対して動作します。パッケージ形式は想定していません(パッケージ形式は単にファイル構造にアクセスすればよいだけなので)。

画像を貼り付けたスライドを表示した状態で本AppleScriptを実行すると、スライド上に貼り付けた画像をデスクトップフォルダに展開し、Previw.appでオープンします。1回実行するとデスクトップに画像ファイルの名前のフォルダが作られ、その中に画像が展開されています。この状態でScriptを再実行すると、フォルダ名が重複するためエラーになります。再実行したい場合にはデスクトップ上の画像名のフォルダを削除しておいてください。

指定Keynote書類の、指定スライド上にある指定イメージについては、ファイル名がわかるだけでパスやデータを取得できるわけではありません。

そこで、フラット形式のKeynote書類中の画像一覧を取得し、このファイル名と符合するものをピックアップします。ただし、ファイル名が完全一致するわけではなく、オリジナルのファイル名が「someImage.png」だった場合に、「someImage-221.png」といったファイル名が見つかります。

また、見つかるのは実ファイルだけでなくプレビュー用の「someImage-small-221.png」といったものも入っています。このプレビュー用イメージについてはスキップしています。

その後、さまざまな処理を行なってもよいでしょうけれども、とりあえず現状ではPreview.appでファイルをオープンしています。

AppleScript名:Keynote書類上の画像をアーカイブ展開して実パスを求めて展開.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/07/04
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

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

tell application "Keynote"
  set dCount to count (every document)
  
if dCount = 0 then return
  
  
tell front document
    set myPath to (file of it)
    
if myPath = missing value then return false –Unsaved
    
    
tell current slide
      tell image 1
        set aFile to file name
        
–> "switchControl.png"
      end tell
    end tell
  end tell
end tell

set myPOSIXPath to POSIX path of (myPath as alias)

–Extract document internal image paths by extracting Keynote’s zip archive
set dList to getInternalImagesWithinKeynote(myPath) of me

–Extract file name and ext from image 1 path
set pPath to POSIX path of aFile
set {aName, aExt} to getExtAndFilenameFromPath(pPath) of me

–Filter Keynote internal image list by image 1’s file name and ext
set theArray to current application’s NSArray’s arrayWithArray:dList
set thePred to current application’s NSPredicate’s predicateWithFormat_("self.pathExtension == %@ && self.lastPathComponent beginswith %@ ", aExt, aName)
set bList to (theArray’s filteredArrayUsingPredicate:thePred) as list
–> {"Data/switchControl-226.png", "Data/switchControl-small-227.png"}

–Extrat file
set exF to false

repeat with i in bList
  set outName to getFilenameAndExtFromPath(i) of me
  
  
if outName does not contain "-small-" then –Skip Preview Image
    set outPath to POSIX path of (path to desktop) & outName
    
set bRes to do shell script "unzip -j " & quoted form of myPOSIXPath & " " & quoted form of i & " -d " & " " & outPath
    
    
set extractPath to POSIX path of (path to desktop) & outName & "/" & outName
    
do shell script "open " & quoted form of extractPath –Open for test
    
    
set exF to true
  end if
end repeat

if exF = false then return false

–Keynote書類中の画像ファイル一覧を取得
on getInternalImagesWithinKeynote(myPath)
  set kPath to POSIX path of myPath
  
set aRes to do shell script "unzip -Z1 " & quoted form of kPath & " | grep ^Data/"
  
set aList to paragraphs of aRes
  
return aList
end getInternalImagesWithinKeynote

–ファイルパスからファイル名部分と拡張子を分離
on getExtAndFilenameFromPath(aPOSIXpath)
  set pathString to current application’s NSString’s stringWithString:aPOSIXpath
  
set aStr to pathString’s lastPathComponent()
  
set aExt to (aStr’s pathExtension())
  
set bStr to aStr’s stringByDeletingPathExtension()
  
return {bStr as string, aExt as string}
end getExtAndFilenameFromPath

–ファイルパスからファイル名部分のみ取得
on getFilenameAndExtFromPath(aPOSIXpath)
  set pathString to current application’s NSString’s stringWithString:aPOSIXpath
  
set aStr to pathString’s lastPathComponent()
  
return aStr as string
end getFilenameAndExtFromPath

★Click Here to Open This Script 

Posted in file Image list | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy Keynote | Leave a comment

指定画像をICNSに変換

Posted on 3月 19, 2020 by Takaaki Naganoya

指定画像をICNS書類に変換するAppleScriptです。

ICNS書類自体は、Classic Mac OS時代にあったアイコンの画像リソースである「icn#」リソースをファイル化したもの、と理解しています(位置付け的に、データ形式とか厳密なレベルで比較したわけではなくて)。

現在では、ICNS書類を作ってアプリケーションアイコンに指定したり、

Xcode上で解像度の異なる画像ファイルをドラッグ&ドロップすると、アプリケーションのICNSファイルを作ってくれます。

Finder上で解像度の異なる画像をフォルダ構造に入れてフォルダの拡張子をつけかえるだけでICNSと認識してくれたような記憶もあります。

そのため、ICNS書類をわざわざScriptから作る需要もないだろうと考えて掲載してこなかったのですが、意外なところでICNS書類の作成を求められました。

自作アプリケーションのカスタム書類を定義して、書類にカスタムアイコンをつけようとしたところ、PNGなどの画像では認識されず、結局ICNS書類を指定する必要に迫られました(意外)。

そんなわけで、いろいろICNS作成Scriptをまとめておきました。

こちらのScriptは実際には実行していませんが、/usr/bin/tiff2icnsコマンドがmacOS 10.15にも含まれていることを確認しています。

AppleScript名:TIFF画像をicnsに変換 v2scpt
tell application "Finder"
  set a to choose file
end tell
set theTiffPath to POSIX path of a
–128 x 128のtiff画像が必要
do shell script "/usr/bin/tiff2icns -noLarge " & (quoted form of theTiffPath)

★Click Here to Open This Script 

こちらは、オープンソースの「IcnsFactory」をフレームワーク化したIconFactory.frameworkを呼び出すバージョンです。自分が実際に使ったのはこちらです。

macOS 10.14以降ではScript Debugger上で実行するか、Script Debuggerから書き出したアプレット(Application(Enhanced))で実行するか、あるいはMacのSIPを解除して実行するなどの方法で実行できます。

Xcode上のAppleScript Applicationプロジェクトに突っ込んで呼び出せば、SIPの解除やScript Debuggerのインストールは必要ありません。

–> Download iconFactory.framework

AppleScript名:画像をICNS書類に
— Created 2017-04-14 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "IconFactory" –https://github.com/kgn/IcnsFactory

set aFile to POSIX path of (choose file)
set outFile to POSIX path of (choose file name)
set anImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile
set iconFam to current application’s IcnsFactory’s writeICNSToFile:outFile withImages:anImage

★Click Here to Open This Script 

Posted in file Image | Tagged 10.13savvy 10.14savvy 10.15savvy | Leave a comment

指定のNSImageにNSBezierPathでclearColor塗りつぶし

Posted on 2月 14, 2020 by Takaaki Naganoya

指定色で塗りつぶしたNSImageを用意し、そこにNSBezierPathでclearColorで塗りつぶし(=切り抜き)を行うAppleScriptです。

2005/8/18にCocoa-dev mailing list に対してStefan Schüßler氏が投稿した内容をもとにしています。いろいろ探して回りましたが、ヒットしたのはこの情報だけでした。彼に感謝を。

Re: [NSColor clearColor] and NSBezierPath: not compatible?

NSBezierPath uses the NSCompositeSourceOver operation, therefore clearColor does not do anything. You could change the graphics state in order to clear the path:

  NSGraphicsContext *context;
  context = [NSGraphicsContext currentContext];
  [context saveGraphicsState];
  [context setCompositingOperation:NSCompositeClear];
  [yourBezierPath fill];
  [context restoreGraphicsState];

Hope this helps.

Stefan
AppleScript名:指定のNSImageにNSBezierPathでclearColor塗りつぶし.scptd
— Created 2020-02-14 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "CoreImage"

property NSColor : a reference to current application’s NSColor
property NSImage : a reference to current application’s NSImage
property NSZeroRect : a reference to current application’s NSZeroRect
property NSBezierPath : a reference to current application’s NSBezierPath
property NSCompositeCopy : a reference to current application’s NSCompositeCopy
property NSGraphicsContext : a reference to current application’s NSGraphicsContext
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSCalibratedRGBColorSpace : a reference to current application’s NSCalibratedRGBColorSpace

set {rCol, gCol, bCol} to choose color

set aNSImage to makeColoredNSImage({rCol, gCol, bCol}, 400, 400) of me
set aPath to generateCircle(200, 100, 100) of me

set bImage to my fillImage:aNSImage withTransparentPathFilling:aPath

set aFile to POSIX path of (choose file name)
set sRes to my saveNSImageAtPathAsPNG(bImage, aFile)

on fillImage:aSourceImg withTransparentPathFilling:aPath
  set aSize to aSourceImg’s |size|()
  
set aWidth to (aSize’s width)
  
set aHeight to (aSize’s height)
  
  
set aRep to NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:aWidth pixelsHigh:aHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0
  
  
NSGraphicsContext’s saveGraphicsState()
  
  
NSGraphicsContext’s setCurrentContext:(NSGraphicsContext’s graphicsContextWithBitmapImageRep:aRep)
  
  
aSourceImg’s drawInRect:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) fromRect:(NSZeroRect) operation:(NSCompositeCopy) fraction:(1.0)
  
  
NSGraphicsContext’s currentContext()’s setCompositingOperation:(current application’s NSCompositeClear)
  
aPath’s fill()
  
  
NSGraphicsContext’s restoreGraphicsState()
  
  
set newImg to NSImage’s alloc()’s initWithSize:(aSize)
  
newImg’s addRepresentation:aRep
  
  
return newImg
end fillImage:withTransparentPathFilling:

on generateCircle(theRadius, x, y)
  set aRect to current application’s NSMakeRect(x, y, theRadius, theRadius)
  
set aCirCle to NSBezierPath’s bezierPath()
  
aCirCle’s appendBezierPathWithOvalInRect:aRect
  
return aCirCle
end generateCircle

on makeColoredNSImage(colList, aWidth, aHeight)
  copy colList to {rCol, gCol, bCol}
  
set aColor to makeNSColorFromRGBA65535val(rCol, gCol, bCol, 1.0) of me
  
set aColoredImage to fillColorWithImage(aColor, aWidth, aHeight) of me
  
return aColoredImage
end makeColoredNSImage

on fillColorWithImage(aColor, aWidth, aHeight)
  set colordImage to makeNSImageWithFilledWithColor(aWidth, aHeight, aColor, aWidth, aHeight) of me
  
colordImage’s lockFocus()
  
colordImage’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 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 NSBezierPath’s bezierPath
  
theNSBezierPath’s appendBezierPathWithRect:theRect
  
—
  
fillColor’s |set|()
  
theNSBezierPath’s fill()
  
—
  
anImage’s unlockFocus()
  
—
  
return anImage
end makeNSImageWithFilledWithColor

on makeNSColorFromRGBA65535val(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer)
  set aRedCocoa to (redValue / 65535) as real
  
set aGreenCocoa to (greenValue / 65535) as real
  
set aBlueCocoa to (blueValue / 65535) as real
  
set aAlphaCocoa to 1.0 as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBA65535val

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

★Click Here to Open This Script 

Posted in Image | Tagged 10.13savvy 10.14savvy 10.15savvy NSBezierPath NSBitmapImageRep NSCalibratedRGBColorSpace NSColor NSCompositeCopy NSGraphicsContext NSImage NSZeroRect | 1 Comment

画像に円を塗る

Posted on 2月 11, 2020 by Takaaki Naganoya

作成した画像(NSImage)に円を塗るAppleScriptです。

最近、6角形の図形ばかり塗りつぶしていましたが、「円に変えるとどうなんだろう?」と考えて、本ルーチンを試作してみました。

ためしに、6角形ではなく円で塗りつぶしてみたものの、そんなにイケていない感じがします。

AppleScript名:画像に円を塗る.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/02/11
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

property aRadius : 40

set aFile to POSIX path of (choose file name)
if aFile does not end with ".png" then
  set aFile to aFile & ".png"
end if

set aColor to current application’s NSColor’s redColor()

set aImage to current application’s NSImage’s alloc()’s initWithSize:{300, 300}

repeat with y from 0 to 300 by aRadius + 4
  repeat with x from 0 to 300 by aRadius + 4
    my drawCircleOnNSIMage(aImage, aRadius, x, y, aColor)
  end repeat
end repeat

set sRes to my saveNSImageAtPathAsPNG(aImage, aFile)

#  MARK: Call By Reference
on drawCircleOnNSIMage(aImage, aRadius, aXpos, aYpos, aColor)
  set aBezier to generateCircle(aRadius, aXpos, aYpos) of me
  (
aImage)’s lockFocus()
  
aColor’s |set|()
  
aBezier’s fill() –ぬりつぶし
  (
aImage)’s unlockFocus()
end drawCircleOnNSIMage

#  MARK: circleのBezier曲線を作成して返す
on generateCircle(theRadius, x, y)
  set aRect to current application’s NSMakeRect(x, y, theRadius, theRadius)
  
set aCirCle to current application’s NSBezierPath’s bezierPath()
  
aCirCle’s appendBezierPathWithOvalInRect:aRect
  
return aCirCle
end generateCircle

# 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

★Click Here to Open This Script 

Posted in file File path Image | Tagged 10.14savvy 10.15savvy NSBezierPath NSBitmapImageRep NSColor NSImage NSPNGFileType NSString | Leave a comment

画像の指定エリアを透明色塗りつぶし(矩形切り抜き)

Posted on 2月 3, 2020 by Takaaki Naganoya

指定画像の指定エリア(矩形)を透明色で塗りつぶすAppleScriptです。透明色で塗りつぶす=矩形で切り抜いたようなかっこうになります。

画像(NSImage)を指定色で塗りつぶすという処理はよく見かけるものですが、clearColor()(透明色)で塗りつぶすという処理を行うとどうなるかといえば…………何も起こりません。

透明色でNSImageを塗りつぶすという処理は、たいへんに「ありそう」な処理ですが、なかなか見つからない。

さんざん探し回ったのですが、自分には見つけられませんでした。ちょうどEdama2さんに相談してみたところ、こういう処理を探し出してもらえました(ありがとうございますー)。ただ、見つけてきた処理そのままでは思い通りの結果にならなかったので、修正が必要であったとのこと。

透明塗りつぶし(切り抜き)の指定座標はCocoaの座標系をそのまま利用しているので、左下が原点です。

NSBezierPathで切り抜き(透明色で塗りつぶし)できるといいのになーという感じではあります。

AppleScript名:画像の指定エリアを透明色塗りつぶし(矩形切り抜き)
— Created 2017-11-19 by Takaaki Naganoya
— Modified 2018-02-14 by Takaaki Naganoya
— Modified 2020-02-03 by Edama2 & Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSUUID : a reference to current application’s NSUUID
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSScreen : a reference to current application’s NSScreen
property NSBezierPath : a reference to current application’s NSBezierPath
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSCompositeClear : a reference to current application’s NSCompositeClear
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep

–切り抜きエリア(複数)
set drawList to {{origin:{x:0, y:0}, |size|:{width:200, height:100}}, {origin:{x:100, y:100}, |size|:{width:50, height:50}}}

set imgPath to POSIX path of (choose file of type {"public.image"})
set anImage to NSImage’s alloc()’s initWithContentsOfFile:imgPath

set fillColor to (NSColor’s colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha:0.9)

–透明色塗りつぶし処理呼び出し
set resImage to drawImageWithClearColorFill(anImage, drawList) of me

set aUUIDstr to (NSUUID’s UUID()’s UUIDString()) as string
set aPath to ((NSString’s stringWithString:imgPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:"png"

set fRes to saveImageRepAtPathAsPNG(resImage, aPath) of me

on drawImageWithClearColorFill(anImage, drawList)
  set retinaF to (NSScreen’s mainScreen()’s backingScaleFactor()) as real
  
–>  2.0 (Retina) / 1.0 (Non Retina)
  
  
set aClearCol to NSColor’s clearColor()
  
set op to current application’s NSCompositeClear
  
  
anImage’s lockFocus() –描画開始
  
  
repeat with i in drawList
    set origX to (x of origin of i) / retinaF
    
set origY to (y of origin of i) / retinaF
    
set sizeX to (width of |size| of i) / retinaF
    
set sizeY to (height of |size| of i) / retinaF
    
    
–Draw Clear Color
    
–http://www.drissman.com/blog/archives/2009/10/09/nsrectfill_and_nscolor_clearcolor.html
    
set theRect to {{x:origX, y:origY}, {width:sizeX, height:sizeY}}
    
aClearCol’s |set|()
    
current application’s NSRectFillUsingOperation(theRect, op)
  end repeat
  
  
anImage’s unlockFocus() –描画ここまで
  
  
return anImage –returns NSImage
end drawImageWithClearColorFill

–画像を指定パスにPNG形式で保存
on saveImageRepAtPathAsPNG(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))
  
return (myNewImageData’s writeToFile:newPath atomically:true) as boolean
end saveImageRepAtPathAsPNG

★Click Here to Open This Script 

Posted in file File path Image | Tagged 10.14savvy 10.15savvy NSBitmapImageRep NSColor NSCompositeClear NSImage NSPNGFileType NSScreen NSString NSUUID | 1 Comment

Keynoteで選択中の画像を特定する

Posted on 1月 22, 2020 by Takaaki Naganoya


Keynoteの書類上で選択中のオブジェクト(image)を特定するAppleScriptです。

Keynoteには、選択中のオブジェクトを求めるという重要な機能「selection」が実装されていません。一応、最新版のKeynoteには「selection」の予約語が存在しているものの、slide中の選択オブジェクトではなく「選択中のスライド」が返ってきます。current slideとほぼ同じ動作です。これでは実用性がいまひとつです。

ないと困るselection(get selected object)ですが、実装されていないのは仕方ありません。

そのものズバリの機能が存在していないものの、他のやりかたで選択中の画像を特定してみました。数が少なかったり重複するものが存在していない場合には有効のようです。

本Scriptでは、Keynote書類上で選択中の画像があるという前提の上で、GUI Scripting経由でコピーを行い、選択対象をクリップボードに入れます。このクリップボード内の画像のサイズを取得。次に、現在のKeynote書類の現在のスライド(ページ)上の画像(imageオブジェクト)のサイズを取得し、順次照合。同じサイズのものがあれば、それが選択中のオブジェクトであると類推します。

かなり穴の多いロジックですが、最初の一歩としては悪くないでしょう。とりあえずは、サイズで比較を行い、同一のものがあれば画像同士の類似性を計算するといった方法も検討できそうです。

お手上げになってしまうのは、画像サイズや内容ともに同一のものが複数あった場合です。その場合を除けば割と識別できそうに思えます。

また、ながらく調査を行なってきた「ローカライズ言語に依存しないGUI Scripting」を用いて選択中のオブジェクトのコピーができるとよさそうです。

AppleScript名:Keynoteで選択中の画像を特定する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/22
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set kRes to getSelectedImage() of me
–> image 3 of slide 24 of document id "534F4E65-4459-4B00-95D4-34C3E020467E"

on getSelectedImage()
  my executeKeynoteItemCopy() –Execute Copy From Menu
  
  
–クリップボードの内容をNSImageに
  
set aNSIMage to my getClipboardASImage()
  
if aNSIMage = false then
    return false
  end if
  
  
–クリップボード中のNSImageのサイズを取得
  
set aSize to aNSIMage’s |size|()
  
set selWidth to (aSize’s width) as real
  
set selHeight to (aSize’s height) as real
  
  
–Keynoteの最前面のドキュメントの現在のスライド上の画像からサイズを取得してクリップボード内の画像サイズと照合する
  
tell application "Keynote"
    tell front document
      tell current slide
        set iList to every image
        
        
repeat with i in iList
          set myHeight to (height of i) as real
          
set myWidth to (width of i) as real
          
if {myWidth, myHeight} = {selWidth, selHeight} then
            return contents of i
          end if
        end repeat
      end tell
    end tell
  end tell
  
return false
end getSelectedImage

— クリップボードの内容をNSImageとして取り出して返す
on getClipboardASImage()
  set theNSPasteboard to current application’s NSPasteboard’s generalPasteboard()
  
set theAttributedStringNSArray to theNSPasteboard’s readObjectsForClasses:({current application’s NSImage}) options:(missing value)
  
if theAttributedStringNSArray = {} then return false
  
set theNSAttributedString to theAttributedStringNSArray’s objectAtIndex:0
  
return theNSAttributedString
end getClipboardASImage

on executeKeynoteItemCopy()
  activate application "Keynote"
  
tell application "System Events"
    tell process "Keynote"
      –click menu item "Copy" of menu 1 of menu bar item "Edit" of menu bar 1
      
click menu item "コピー" of menu 1 of menu bar item "編集" of menu bar 1
    end tell
  end tell
end executeKeynoteItemCopy

★Click Here to Open This Script 

Posted in Clipboard GUI Scripting Image | Tagged 10.14savvy 10.15savvy Keynote NSImage NSPasteboard | Leave a comment

画像の空白判定 v4

Posted on 12月 19, 2019 by Takaaki Naganoya

画像のすべてのピクセルが白であることをチェックするAppleScriptです。

以前にmacOS 10.12上で作成した「空白画像検出v3」は一般的に処理時間のかかる空白画像の検出(ヒストグラム計算してチェックする?)が高速に処理できます(GPUImageでヒストグラム計算を行うより2倍ぐらい高速)。空白検出のためだけにAdobe Photoshopが必要になるといった事態は避けられます。

–> test Data(動作検証用各種テストデータ)

macOS 10.14.6上でこのルーチンを再度試してみたところ、思ったとおりに空白検出(数百万ピクセルの画像でも1つだけ黒であればfalseを返す)してくれません。ちょっと書き方を変えていますが、単体で通常のAppleScript(Cocoa不使用)にコンテクストメニューから突っ込むモジュールとして運用するためです。

copyコマンドがdeep copyしてくれない?

参照ではなくすべてのデータをコピーするコマンドとして、copyコマンドはとても重宝しています。単に「パラメータの代入の方向が違う偏屈なコマンド」ではなく、明示的にデータ内容をコピーするためのコマンドと認識しています。

AppleScriptのオブジェクト同様、Cocoaのオブジェクトについてもcopyコマンドでdeep copyしてくれるものと理解していましたが、macOS 10.14.6上で本ルーチンを試してみたところ、どうも参照をコピーしている気配がします。

AppleScriptのオブジェクト(配列とか)をcopyコマンドでコピーすると、参照ではなくデータが複製されていることを確認しました。Cocoaオブジェクトのcopyも同様かどうかは、ちょっとそうじゃないんじゃないかというところです。

set bNSImage to aNSImage's |copy|()

Cocoaの世界のオブジェクトのコピーはこんな感じ(↑)でできたので、今後はこちらを採用することにします。

1×1のNSImageに色を塗るとデータサイズが増える

ビットマップ画像の状態であるNSBitmapImageRepになっていれば、1×1画像のサイズは同じことが期待されます。実際、macOS 10.12上ではそのように扱えていました。

ところが、macOS 10.14上で1×1ドットのNSImageに対して色を塗って、NSBitmapImageRepを取得すると、塗らない状態のNSImageよりもデータ(NSData)サイズが大きくなることがわかりました。


▲1×1のPNG画像をビットマップ化したデータ。赤が処理前、青が塗りつぶし処理後のデータ(macOS 10.14.6)。ピクセル数が増えてるのでは? と疑ってサイズを何回も計算して確認しましたが、間違っていません

しかも、データ量がmacOS 10.14と10.15では大幅に異なります(macOS 10.15では大幅にデータ量が減る)。

 1×1 PNG画像 ビットマップ化したデータサイズ:3,354 Bytes(macOS 10.14.6)
 1×1 PNG画像 塗りつぶし ビットマップ化したデータサイズ:3,574 Bytes(macOS 10.14.6)
 1×1 PNG画像 塗りつぶし ビットマップ化したデータサイズ:750 Bytes(macOS 10.15.2)

さすがに匙を投げかけましたが、比較元のデータに透明の色(clearColor())を塗る=画像的に意味はないが、同じ処理を通すことでデータサイズを同程度にするという処理を行うことで、いい感じに空白検出できるようになりました。

なにをどういじくったら、1×1ビットマップ画像のサイズがOSアップデートごとに大幅に変わるのかさっぱり理解できないのですが、そこに何か意味があるのでしょうか?

Mac App Storeに出したアプリケーションで、PDFの空白ページ検出に本ルーチンを利用していますが、Appleのレビュー段階で「単にPDFから文字を抽出して空白検出しているのだろう」と思われてリジェクトされました。実際には、全ページを画像レンダリングして1ドットの画像でも存在していたら空白としては認識しない仕様になっているのですが、Appleのレビューワーには処理内容を説明して、各種ベンチマーク結果などを出さないと信じてもらえませんでした。

Appleのエンジニアが考えるところの空白検出が「文字チェックだけ」の使い物にならない処理だということはよくわかりました。また、頭からそのように思い込んで攻撃してきた間抜けにも遭遇してウンザリしました。

AppleScript名:画像の空白判定 v4
set aFile to (choose file of type {"public.image"})
set iRes to checkImageIsWhite(aFile) of whiteImageKit
–> true –white (blank) image

script whiteImageKit
  use AppleScript version "2.7" — High Sierra (10.13) or later
  
use framework "Foundation"
  
use framework "AppKit"
  
use scripting additions
  
property parent : AppleScript
  
  
property NSData : a reference to current application’s NSData
  
property NSDate : a reference to current application’s NSDate
  
property |NSURL| : a reference to current application’s |NSURL|
  
property NSColor : a reference to current application’s NSColor
  
property NSImage : a reference to current application’s NSImage
  
property NSBezierPath : a reference to current application’s NSBezierPath
  
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
  
  
–Compare Original Data and
  
on checkImageIsWhite(aFile)
    set aPOSIXpath to POSIX path of aFile
    
set aURL to |NSURL|’s fileURLWithPath:(aPOSIXpath)
    
    
set aNSImage to NSImage’s alloc()’s initWithContentsOfURL:(aURL)
    
set bNSImage to NSImage’s alloc()’s initWithContentsOfURL:(aURL)
    
    
–copy aNSImage to bNSImage–Not deep copy ????
    
    
set fillColor1 to NSColor’s clearColor()
    
set blankNSImage1 to drawImageWithFilledColor(aNSImage, fillColor1) of me
    
    
set fillColor2 to makeNSColorFromRGBAval(65535, 65535, 65535, 65535, 65535) of me
    
set blankNSImage2 to drawImageWithFilledColor(bNSImage, fillColor2) of me
    
    
set aTiff to blankNSImage1’s TIFFRepresentation()
    
set bTiff to blankNSImage2’s TIFFRepresentation()
    
    
set chkWhite to (aTiff’s isEqualToData:bTiff) as boolean
    
    
return chkWhite
  end checkImageIsWhite
  
  
  
on getSizeOfImage(anNSImage)
    set aSize to anNSImage’s |size|()
    
set aClass to class of aSize
    
if aClass = record then
      copy aSize to theSize –To macOS 10.12.x
    else –macOS 10.13 or later
      set sizeX to (item 1 of item 2 of aSize)
      
set sizeY to (item 2 of item 2 of aSize)
      
set theSize to {width:sizeX, height:sizeY}
    end if
    
return theSize
  end getSizeOfImage
  
  
  
–指定サイズの画像を作成し、背景を指定色で塗る
  
on drawImageWithFilledColor(anImage, fillColor)
    set aSize to getSizeOfImage(anImage) of me
    
    
anImage’s lockFocus()
    
    
set theRect to {{x:0, y:0}, {width:(width of aSize), height:(height of aSize)}}
    
set theNSBezierPath to NSBezierPath’s bezierPath
    
theNSBezierPath’s appendBezierPathWithRect:theRect
    
fillColor’s |set|()
    
theNSBezierPath’s fill()
    
    
anImage’s unlockFocus()
    
    
return anImage
  end drawImageWithFilledColor
  
  
  
–aMaxValを最大値とする数値でNSColorを作成して返す
  
on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
    set aRedCocoa to (redValue / aMaxVal) as real
    
set aGreenCocoa to (greenValue / aMaxVal) as real
    
set aBlueCocoa to (blueValue / aMaxVal) as real
    
set aAlphaCocoa to (alphaValue / aMaxVal) as real
    
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
    
return aColor
  end makeNSColorFromRGBAval
  
end script

★Click Here to Open This Script 

Posted in Image | Tagged 10.13savvy 10.14savvy 10.15savvy NSBezierPath NSBitmapImageRep NSColor NSData NSImage NSURL | 3 Comments

Continuity Camera AS

Posted on 12月 12, 2019 by Takaaki Naganoya

Xcode上でCocoa AppleScriptアプリケーションを作成し、macOS 10.14から搭載された「Continuity Camera」の機能を利用して、iOSデバイス上で撮影した写真をその場でMacに転送・保存してみました。

–> ContinityCameraAS(Xcode 11 Project)

Continuity Cameraをサポートする部分のObjective-CのコードはThomas Zoechling氏のBlog上のものを利用させていただいております。

本当は通常のスクリプトでdisplay dialog的なダイアログを表示して、その上に作成したNSImageViewでContinuity Cameraを呼び出せるとよかったのですが、なかなかそこまで噛み砕いて解釈できなかったので、Xcode上のアプリそのままです。

Continuity CameraのプロジェクトをXcode上でビルド&実行すると、なにもないっぽいWindowが表示されますが、下地にNSImageViewを敷いてあるような気がします。このウィンドウの真ん中の方でControl-クリックあるいはマウスの右ボタンをクリックすると、コンテクストメニューが表示され、そこでカメラから画像取り込みを行うデバイスを選択し、それらの周辺デバイスで撮影した写真をそのまま取り込めます。

Continuity Camera機能は、同じiCloud IDで関連づけたiOSデバイスのカメラを無線LANのネットワークごしにMacから利用するものと理解しています(Bluetoothもオンにする必要があるかもしれない)。

ウィンドウ上の「Save Image」ボタンをクリックすると、その内容をデスクトップにPNG画像で保存します。

AppleScriptアプリケーションでもContinuity Cameraを利用できることがわかったので、このプログラムにAppleScript用語辞書(sdef)をつけてScriptableなアプリケーションに仕立て上げれば、通常のAppleScriptからcapture cameraといったコマンドで取り込めてよいのではないでしょうか。

コンテクストメニューの先にある機能に直接アクセスするためには、もう少し調べる必要がありそうではあります。

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— continityCameraAS
—
— Created by Takaaki Naganoya on 2019/10/21.
— Copyright © 2019 Takaaki Naganoya. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
property theImageV : missing value
  
  
on applicationWillFinishLaunching:aNotification
    — Insert code here to initialize your application before any files are opened
  end applicationWillFinishLaunching:
  
  
  
on applicationShouldTerminate:sender
    — Insert code here to do any housekeeping before your application quits
    
return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
  
on clicked:aSender
    set imgRes to theImageV’s image()
    
set dtPath to POSIX path of (path to desktop)
    
log {"dtPath", dtPath}
    
set fRes to retUUIDfilePath(dtPath, "png") of me
    
log {"fRes", fRes}
    
set sRes to saveNSImageAtPathAsPNG(imgRes, fRes) of me
  end clicked:
  
  
  
–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 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 stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
    
return aPath
  end retUUIDfilePath
  
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode Image | Tagged 10.14savvy 10.15savvy | Leave a comment

Double PDF v2.0完成に近づく

Posted on 11月 29, 2019 by Takaaki Naganoya

Mac App Storeで販売したはいいものの、途中(macOS 10.13)でド派手なバグをOS(PDFView)に作られ、AppleのDevelopper Supportに正式に連絡してもなしのつぶてでそのままMac App Storeに置かれている「Double PDF」。さすがに現状のままだとまずすぎるので、macOS 10.14/10.15上で動作するように改修作業を行なっている今日このごろ(macOS 10.13.xでは、動くことは動くんですがOS自体の未修正バグが多すぎて動作保証いたしかねます)。

# OSをアップデートすると機能が落ちるとは何事だろう?

PDFViewのド派手なバグ(currentPageを取得できない)を回避するために、自前でAppleScriptでいろいろ回避コードを走らせているので、ページめくりのスピードが落ちています(個人的にこれのために作ったので、テンションが落ちるところです)。

初版では画像処理にGPUImage.frameworkを同梱して利用していましたが、GPUImage1だとOpenGL経由でGPUの機能にアクセスしており、OpenGL自体が最新のmacOS 10.15では非推奨となっており、Mac App Storeでリジェクトされる危険性があります(より新しい代替APIであるMetalを使わないと因縁を付けられる気が、、、)。

そこで、GPUImageに依存しているコードをすべて書き換え、GPUImageを完全に取り外しました。これには、よくよく調べたら、PDFの各ページをグレースケール画像に変換する箇所でしか利用していなかったことが大きいです。これで、名実ともに「すべてAppleScriptで記述したアプリケーション」に。

GPUImageの除去は使い勝手には一切影響しません。若干の前向きな機能追加も行なっておきましょう。

これまでに意見として寄せられていないものの、どうもグレースケール画像で比較を行うことに不満を持っていたユーザーが一定数いるものとにらんでいたので、カラーのまま比較する機能を追加しました。

正直なところ、「カラー比較モード」は個人的には不要と思っている(文字主体の書籍の校正用に作った)のですが、念のためです。

Double PDFはデータ上のささいな違いを「見逃す」ように作ってあります。これは、Adobe AcrobatのPDF比較機能が、見た目には影響を及ぼさないデータ上の些細な違いばかりピックアップして実用性がまったくないことから思いついたものです。見た目に影響のない差異を見逃して、見た目や文字で差が発生している箇所を指摘するツールという味付けになっています。

画像サイズを小さくした上でグレースケール化して比較するのはそのための重要な機能です。ただ、間違って色が変わったことを検出したいような用途もあることでしょう。

あとは、PDFからテキスト抽出をしたときに、PDF書き出し時の環境(OSバージョン)によってはNo Width Spaceが検出されるものがあるため、No Width Spaceの削除機能を追加しました。

細かい箇所でまだ不具合点(右側のビューワーのノンブルが表示されないことがある)がありますが、とりあえず出してみてもよさそうな気配はしています。

地味なところで画像素材をDark Mode対応させました。Credits.rtfのダークモード対応など、地味に工数が増えるのは勘弁してほしいです。あとは、外部アプリケーション操作要求を行うためのInfo.plistのエントリ追加などもあります。これを追加しないと外部アプリケーションへの操作要求のダイアログ自体が出ない=一切操作できないので要注意点です。

ほかにも、現行のXcodeでCocoa AppleScriptアプリケーションのプロジェクトを作ると、デフォルトではソースコード開示状態のビルドセッティングになってしまうので、これも要チェック点でしょう。まさかと思ってこの設定を再確認してみたら、execute onlyになっていませんでした。怖すぎ、、、

Posted in AppleScript Application on Xcode Image PDF | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 13.6.5 AS系のバグ、一切直らず
  • macOS 15, Sequoia
  • 初心者がつまづきやすい「log」コマンド
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • メキシカンハットの描画
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • Numbersで選択範囲のセルの前後の空白を削除
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • AppleScriptによる並列処理
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScript入門③AppleScriptを使った「自動化」とは?

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (188) 14.0savvy (138) 15.0savvy (116) CotEditor (64) Finder (51) iTunes (19) Keynote (115) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (75) Pages (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC