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

カテゴリー: file

Finderで選択中のPDFを古い順に連結する v2

Posted on 5月 27, 2018 by Takaaki Naganoya

Finder上で選択中のファイルのうちPDFだけを作成日付で古い順に連結するAppleScriptです。

間違ってPDF以外のファイルを選択してしまった場合でも、それについては無視します。

こんな風にmacOS標準装備のScript Menuに入れて利用しています。

AppleScript名:Finderで選択中のPDFを古い順に連結する v2
— Created 2018-05-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"

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 NSFileManager : a reference to current application’s NSFileManager
property NSURLPathKey : a reference to current application’s NSURLPathKey
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property NSURLContentModificationDateKey : a reference to current application’s NSURLContentModificationDateKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles

–set inFiles to (choose file of type {"pdf"} with prompt "Choose your PDF files:" with multiple selections allowed)
tell application "Finder"
  set inFiles to selection as alias list
end tell

if inFiles = {} then return

–指定のAlias listのうちPDFのみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "com.adobe.pdf") of me

–選択中のファイルのうちの1つから親フォルダを求め、出力先ファイルパスを組み立てる
set outPathTarg to POSIX path of (first item of filRes1)
set pathString to current application’s NSString’s stringWithString:outPathTarg
set newPath to (pathString’s stringByDeletingLastPathComponent()) as string
set destPosixPath to newPath & "/" & ((current application’s NSUUID’s UUID()’s UUIDString()) as string) & ".pdf"

combinePDFsAndSaveIt(filRes1, destPosixPath) of me

on combinePDFsAndSaveIt(inFiles, destPosixPath)
  set inFilesSorted to my filesInListSortFromOldToNew(inFiles)
  
  
— make URL of the first PDF
  
set inNSURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of item 1 of inFilesSorted)
  
set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:inNSURL
  
  
— loop through the rest
  
set oldDocCount to theDoc’s pageCount()
  
set inFilesSorted to rest of inFilesSorted
  
  
repeat with aFile in inFilesSorted
    set inNSURL to (current application’s |NSURL|’s fileURLWithPath:(POSIX path of aFile))
    
set newDoc to (current application’s PDFDocument’s alloc()’s initWithURL:inNSURL)
    
    
set newDocCount to newDoc’s pageCount()
    
repeat with i from 1 to newDocCount
      set thePDFPage to (newDoc’s pageAtIndex:(i – 1)) — zero-based indexes
      (
theDoc’s insertPage:thePDFPage atIndex:oldDocCount)
      
set oldDocCount to oldDocCount + 1
    end repeat
    
  end repeat
  
  
set outNSURL to current application’s |NSURL|’s fileURLWithPath:destPosixPath
  (
theDoc’s writeToURL:outNSURL)
end combinePDFsAndSaveIt

on filesInListSortFromOldToNew(aliasList)
  set keysToRequest to {NSURLPathKey, NSURLIsPackageKey, NSURLIsDirectoryKey, NSURLContentModificationDateKey}
  
  
set valuesNSArray to NSMutableArray’s array()
  
repeat with i in aliasList
    set oneNSURL to (|NSURL|’s fileURLWithPath:(POSIX path of i))
    (
valuesNSArray’s addObject:(oneNSURL’s resourceValuesForKeys:keysToRequest |error|:(missing value)))
  end repeat
  
  
set theNSPredicate to NSPredicate’s predicateWithFormat_("%K == NO OR %K == YES", NSURLIsDirectoryKey, NSURLIsPackageKey)
  
set valuesNSArray to valuesNSArray’s filteredArrayUsingPredicate:theNSPredicate
  
  
set theDescriptor to NSSortDescriptor’s sortDescriptorWithKey:(NSURLContentModificationDateKey) ascending:true
  
set theSortedNSArray to valuesNSArray’s sortedArrayUsingDescriptors:{theDescriptor}
  
  
— extract just the paths and convert to an AppleScript list
  
return (theSortedNSArray’s valueForKey:(NSURLPathKey)) as list
end filesInListSortFromOldToNew

–Alias listから指定UTIに含まれるものをPOSIX pathのリストで返す
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
    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

★Click Here to Open This Script 

Posted in file PDF Sort UTI | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finderで選択中のファイルのうち、指定UTIに含まれるものを返す

Posted on 5月 26, 2018 by Takaaki Naganoya

Finder上で選択中のファイルのうち、指定UTIに含まれるもの(下位階層のUTIも含む)を返すAppleScriptです。

Finderでfileのkindを指定してフィルタ参照でしぼりこむ方法もありますが、ファイル数が増えると処理速度が大幅に低下するのと、UTIで指定できたほうが便利なので作っておきました。

AppleScript名:Finderで選択中のファイルのうち、指定UTIに含まれるものを返す
— Created 2018-05-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

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 selection as alias list
end tell
if aSel = {} then its return

set filRes1 to filterAliasListByUTI(aSel, "com.adobe.pdf") of me
–>  {​​​​​"/Users/me/Pictures/annotation_origin.pdf"​​​}

set filRes2 to filterAliasListByUTI(aSel, "public.image") of me
–>  {"/Users/me/Pictures/スクリーンショット 2017-11-06 20.05.30.png", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.35.08.png", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.33.53.png", "/Users/me/Pictures/スクリーンショット 2017-09-26 16.46.29.png"}

set filRes3 to filterAliasListByUTI(aSel, "public.item") of me
–>  {"/Users/me/Pictures/スクリーンショット 2017-11-06 20.05.30.png", "/Users/me/Pictures/annotation_origin.pdf", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.35.08.png", "/Users/me/Pictures/スクリーンショット 2017-09-27 19.33.53.png", "/Users/me/Pictures/スクリーンショット 2017-09-26 16.46.29.png"}

–Alias listから指定UTIに含まれるものをPOSIX pathのリストで返す
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
    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

★Click Here to Open This Script 

Posted in file UTI | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Keynoteスライドの末尾にQRコードのスライドを追加

Posted on 5月 17, 2018 by Takaaki Naganoya

指定の連絡先情報のQRコード画像を作成して、現在オープン中のKeynoteのスライドの末尾に追加するAppleScriptです。

–> Watch Demo Movie

このAppleScriptでは、ただ固定の文字列をQRコード画像化していますが、Contacts(連絡先)から自分の連絡先の情報を取得して、そこからQRコード画像を作成すると、より「AppleScriptらしい」自動処理になると思います。

さらに、このKeynoteのスライドからPDFを書き出して、Slide Shareに自動アップロードし、そのURLもQRコード画像の中に入れると文句のつけようがありません。

AppleScriptによる自動化で「単なる1つのコマンドをScriptから呼び出すだけ」のものを大量に見かけますが、それだとほとんど意味がありません。複数のアプリケーションや複数のサービスを呼び出してそれらを連携させてはじめて「自動化する意味がある」内容になります。

AppleScript名:Keynoteスライドの末尾にQRコードのスライドを追加
— Created 2018-05-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"

–QRCodeを作成
set a to "MEMORY:Piyomaru Software
NAME1:長野谷 隆昌
NAME2:ながのや たかあき
TEL1:080-xxxx-xxxxx
MAIL1:maro@piyocast.com
TEL2:080-xxxx-xxxxx
MAIL2:maro@xxxxxxxxx
MECARD:N:長野谷,隆昌;SOUND:ながのや,たかあき;TEL:080-9999-9999;TEL:03-9999-9999;EMAIL:maro@piyocast.com;EMAIL:maro@xxxxx.xxxxx;NOTE:ぴよまる;;"

set savedPath to makeQRCodeImageOnDesktop(a) of me
set savedFile to (POSIX file savedPath)
set savedAlias to savedFile as alias

tell application "Keynote"
  tell front document
    set endSlide to make new slide at end
    
    
set blankMaster to master slide "空白" –"Blank" in Japanese. This string is *localized*
    
    
tell endSlide
      set base slide to blankMaster
      
set thisImage to make new image with properties {file:savedAlias}
    end tell
  end tell
end tell

do shell script "rm -f " & quoted form of savedPath

on makeQRCodeImageOnDesktop(aData)
  set aStr to current application’s NSString’s stringWithString:aData
  
set strData to aStr’s dataUsingEncoding:(current application’s NSShiftJISStringEncoding) –シフトJISにエンコード
  
set qrFilter to current application’s CIFilter’s filterWithName:"CIQRCodeGenerator"
  
qrFilter’s setValue:strData forKey:"inputMessage"
  
qrFilter’s setValue:"H" forKey:"inputCorrectionLevel"
  
set anImage to qrFilter’s outputImage()
  
  
set convImg to convCIimageToNSImage(anImage) of me
  
  
–NSImageを拡大(アンチエイリアス解除で)
  
set resizedImg to my resizeNSImageWithoutAntlialias:convImg toScale:6.0
  
  
–デスクトップに保存
  
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(resizedImg, savePath) of me
  
  
return savePath as string
end makeQRCodeImageOnDesktop

on convCIimageToNSImage(aCIImage)
  set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

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 as string
end convNSImageToCIimage

–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

–NSImageを指定倍率で拡大(アンチエイリアス解除状態で)–By Shane Stanley
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:

★Click Here to Open This Script 

Posted in file QR Code | Tagged 10.12savvy 10.13savvy Keynote | 1 Comment

自然言語で指定した日時以降に作成されたファイルをSpotlight検索

Posted on 5月 3, 2018 by Takaaki Naganoya
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

★Click Here to Open This Script 

Posted in Calendar file Spotlight | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Markdownのimglinkタグ行のリンク書き換え

Posted on 5月 3, 2018 by Takaaki Naganoya

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

★Click Here to Open This Script 

Posted in file File path Markdown Spotlight Text | Tagged 10.11savvy 10.12savvy 10.13savvy MacDown | Leave a comment

AS構文色分け情報の重複チェック

Posted on 4月 23, 2018 by Takaaki Naganoya

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

★Click Here to Open This Script 

Posted in file list OSA Record | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

指定パスのAppleScript書類の内容をURL文字列化 v3

Posted on 4月 22, 2018 by Takaaki Naganoya

指定した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

★Click Here to Open This Script 

Posted in file OSA | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定パスのAppleScript書類の内容をURL文字列化 v2

Posted on 4月 21, 2018 by Takaaki Naganoya

指定した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

★Click Here to Open This Script 

Posted in file OSA | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Finderの最前面のアイコン表示ウィンドウ上の画像をY座標の情報をキーにして縦連結

Posted on 4月 18, 2018 by Takaaki Naganoya

Finderの最前面のWindowがアイコン表示になっている場合に、Window(Folder)内の画像ファイルをFinder上でのアイコン位置情報(Y座標のみ)を考慮して縦方向に1枚ものの画像に結合するAppleScriptです。

–> Demo Movie

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

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Finderの最前面のアイコン表示ウィンドウ上の画像をX座標の情報をキーにして横連結

Posted on 4月 17, 2018 by Takaaki Naganoya

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

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

エイリアス書類からオリジナルファイルの情報を取得する

Posted on 4月 16, 2018 by Takaaki Naganoya

指定のエイリアス書類から、オリジナルファイルの情報を取得する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

★Click Here to Open This Script 

Posted in file | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

指定フォルダのサブフォルダの中からYYYY_MM_DDで最新のものを抽出してFinderでオープン

Posted on 4月 11, 2018 by Takaaki Naganoya

指定フォルダ以下に存在する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

★Click Here to Open This Script 

Posted in file | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finder上で選択中の画像を縦方向に連結 v1

Posted on 4月 8, 2018 by Takaaki Naganoya

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:

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

配列に入れた画像を類似度でソートする

Posted on 4月 7, 2018 by Takaaki Naganoya

ターゲット画像に対して配列に入れた複数の画像を類似度をキーにしてソートする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

★Click Here to Open This Script 

Posted in file Image Sort | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

2つの画像が類似しているかを判定

Posted on 4月 7, 2018 by Takaaki Naganoya

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

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | 2 Comments

NSImageをリサイズ(アンチエイリアス解除)pattern 4

Posted on 4月 7, 2018 by Takaaki Naganoya

指定ファイルを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

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

画像中の色の置き換え

Posted on 4月 7, 2018 by Takaaki Naganoya

指定画像中の指定色を置き換える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

★Click Here to Open This Script 

Posted in Color file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定画像の余白の自動トリミング

Posted on 4月 7, 2018 by Takaaki Naganoya

指定画像の余白トリミングを自動で行う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

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | 2 Comments

NSImageの垂直、水平反転

Posted on 4月 7, 2018 by Takaaki Naganoya

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

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

単色画像(アルファ値必要)に色を指定して塗りつぶし

Posted on 4月 7, 2018 by Takaaki Naganoya

単色画像に色を指定して塗りつぶしを行う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

★Click Here to Open This Script 

Posted in Color file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | 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