Icon

Icon Composer

Posterannotate1_2x720x443

| | コメント (0)

ICNSファイルから各サイズのPNG画像の取り出し 少し修正

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

ICNS2PNG.applescript
ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(* ICNSファイルから各サイズのPNG画像を取り出します
004v1.1 書き込みアクセス権の無い場所のファイル選んだ場合の対応を加えた
005
006
007com.cocolog-nifty.quicktimer.icefloe *)
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009use AppleScript version "2.8"
010use framework "Foundation"
011use framework "AppKit"
012use scripting additions
013
014property refMe : a reference to current application
015
016
017##################
018#入力ダイアログ
019#デフォルトロケーション
020set appFileManager to refMe's NSFileManager's defaultManager()
021set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
022set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
023set aliasPicturesDirPath to (ocidPicturesDirPathURL's absoluteURL()) as alias
024#ダイアログを前面に出す
025set strName to (name of current application) as text
026if strName is "osascript" then
027   tell application "Finder" to activate
028else
029   tell current application to activate
030end if
031#ダイアログ
032set listUTI to {"com.apple.icns"}
033set strMes to ("ICNSファイルを選んでください") as text
034set strPrompt to ("ICNSファイルを選んでください") as text
035try
036   set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasPicturesDirPath of type listUTI with invisibles, showing package contents and multiple selections allowed) as list
037on error
038   return "エラーしましたA"
039end try
040##################
041#処理開始
042repeat with itemAliasFilePath in listAliasFilePath
043   set aliasFilePath to itemAliasFilePath as alias
044   ##################
045   #入力パス
046   set strFilePath to (POSIX path of aliasFilePath) as text
047   set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
048   set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
049   set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
050   #保存用のディレクトリ名を作っておく iconsetを強制
051   set ocidFileName to ocidFilePathURL's lastPathComponent()
052   set ocidBaseFilePath to ocidFileName's stringByDeletingPathExtension()
053   set ocidSaveDirName to (ocidBaseFilePath's stringByAppendingPathExtension:("iconset"))
054   
055   ##################
056   #出力先 
057   set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
058   set ocidSaveDirPathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:(ocidSaveDirName) isDirectory:(true))
059   #フォルダを作っておく
060   set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
061   (ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions))
062   set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
063   
064   ##################
065   #読み込みNSDATA
066   set ocidOption to (refMe's NSDataReadingMappedIfSafe)
067   set listResponse to (refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error|:(reference))
068   if (item 2 of listResponse) = (missing value) then
069      log "正常処理"
070      set ocidFolderIconData to (item 1 of listResponse)
071   else if (item 2 of listResponse) ≠ (missing value) then
072      log (item 2 of listResponse)'s code() as text
073      log (item 2 of listResponse)'s localizedDescription() as text
074      return "エラーしましたB"
075   end if
076   
077   ##################
078   #NSDATANSIMAGE
079   set ocidFolderIconImage to (refMe's NSImage's alloc()'s initWithData:(ocidFolderIconData))
080   
081   ##################
082   #representations
083   set ocidImageRepArray to ocidFolderIconImage's representations()
084   #順番の処理
085   repeat with itemImgRep in ocidImageRepArray
086      ##################
087      #サイズ取得して保存パスを作成
088      #ピクセルサイズを取得
089      set ocidPixelsHigh to itemImgRep's pixelsHigh()
090      set ocidPixelsWide to itemImgRep's pixelsWide()
091      #ポイントサイズ
092      set ocidPtSize to itemImgRep's |size|()
093      set ocidPointHigh to ocidPtSize's width()
094      set ocidPontWide to ocidPtSize's height()
095      #解像度
096      set numResolution to (ocidPixelsWide / ocidPontWide) as integer
097      #ファイル名にしていく
098      if numResolution = 2 then
099         set strSaveFileName to ("icon_" & (ocidPontWide as integer) & "x" & (ocidPointHigh as integer) & "@2x.png") as text
100      else
101         set strSaveFileName to ("icon_" & ocidPixelsWide & "x" & ocidPixelsHigh & ".png") as text
102      end if
103      #保存先のパスにしておく
104      set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
105      ##################
106      #イメージを保存用に変換
107      #変換オプション
108      set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
109      (ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
110      (ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
111      #変換
112      set ocidType to (refMe's NSBitmapImageFileTypePNG)
113      set ocidNSInlineData to (itemImgRep's representationUsingType:(ocidType) |properties|:(ocidProperty))
114      #保存
115      set ocidOption to (refMe's NSDataWritingAtomic)
116      set listDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference))
117      if (item 1 of listDone) is true then
118         log "正常処理"
119      else if (item 2 of listDone) ≠ (missing value) then
120         log (item 2 of listDone)'s code() as text
121         log (item 2 of listDone)'s localizedDescription() as text
122         #
123         set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
124         set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
125         #
126         set ocidSaveDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GetIcon") isDirectory:(true))
127         #
128         set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
129         # 777-->511 755-->493 700-->448 766-->502 
130         (ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions))
131         set ocidMakeDirPath to ocidSaveDirPathURL's |path|()
132         set boolDirExists to (appFileManager's fileExistsAtPath:(ocidMakeDirPath) isDirectory:(true))
133         if boolDirExists is false then
134            set listDone to (appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference))
135            if (item 1 of listDone) is false then
136               set strErrorNO to (item 2 of listDone)'s code() as text
137               set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
138               refMe's NSLog("■" & strErrorNO & strErrorMes)
139               log "createDirectoryAtURL エラーしました" & strErrorNO & strErrorMes
140               return false
141            end if
142         end if
143         set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
144         set listDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error|:(reference))
145         
146      end if
147      
148   end repeat
149   
150end repeat
151
152##保存先を開く
153set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
154set boolDone to appSharedWorkspace's openURL:(ocidSaveDirPathURL)
155
156return
AppleScriptで生成しました

| | コメント (0)

フォルダ内の指定拡張子を収集する(アイコン用)

フォルダ内のアイコンファイルの収集用ですが
拡張子を変更すれば色々なファイルを収集するように変更できます
フォルダ内のicns収集.scpt
フォルダ内のicns収集.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# ループ処理にallObjectsを利用
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007##自分環境がos12なので2.8にしているだけです
008use AppleScript version "2.8"
009use framework "Foundation"
010use framework "AppKit"
011use scripting additions
012property refMe : a reference to current application
013#############################
014#設定項目 収集する拡張子
015set strExtName to ("icns") as text
016#同名ファイル何回まで別名収集するか
017set numCntRename to 10 as integer
018
019#############################
020###ダイアログを前面に出す
021set strName to (name of current application) as text
022if strName is "osascript" then
023  tell application "SystemUIServer" to activate
024else
025  tell current application to activate
026end if
027############
028set appFileManager to refMe's NSFileManager's defaultManager()
029set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
030set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
031set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
032############
033set strMes to "フォルダを選んでください" as text
034set strPrompt to "フォルダを選択してください" as text
035try
036  tell application "SystemUIServer"
037    #Activateは必須
038    activate
039    set aliasDirPath to (choose folder strMes with prompt strPrompt default location aliasDefaultLocation with invisibles and showing package contents without multiple selections allowed) as alias
040  end tell
041on error
042  log "エラーしました"
043  return "エラーしました"
044end try
045############
046#パス
047set strDirPath to (POSIX path of aliasDirPath) as text
048set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
049set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
050set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
051set ocidDirName to ocidDirPathURL's lastPathComponent()
052set ocidBaseDirName to ocidDirName's stringByDeletingPathExtension()
053
054############
055#コンテンツの収集
056#プロパティ
057set ocidPropertiesArray to refMe's NSMutableArray's alloc()'s init()
058ocidPropertiesArray's addObject:(refMe's NSURLIsDirectoryKey)
059ocidPropertiesArray's addObject:(refMe's NSURLNameKey)
060ocidPropertiesArray's addObject:(refMe's NSURLPathKey)
061#オプション
062set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
063#収集
064set ocidEmuDict to appFileManager's enumeratorAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidPropertiesArray) options:(ocidOption) errorHandler:(reference)
065
066#出力用の空の可変リスト
067set ocidIcnsPathURLAllArray to refMe's NSMutableArray's alloc()'s init()
068############
069#allObjectsでループする方法
070set ocidEmuFileURLArray to ocidEmuDict's allObjects()
071repeat with itemURL in ocidEmuFileURLArray
072  set ocidExtensionName to itemURL's pathExtension()
073  #アイコンファイルを追加
074  set boolEqual to (ocidExtensionName's isEqualToString:(strExtName))
075  if boolEqual is true then
076    #出力用のリストに追加していく
077    (ocidIcnsPathURLAllArray's addObject:(itemURL))
078  end if
079  #拡張子大文字も一応確認
080  set ocidExtName to (refMe's NSString's stringWithString:(strExtName))
081  set ocidExtNameUpper to ocidExtName's uppercaseString()
082  set boolEqual to (ocidExtensionName's isEqualToString:(ocidExtNameUpper))
083  if boolEqual is true then
084    #出力用のリストに追加していく
085    (ocidIcnsPathURLAllArray's addObject:(itemURL))
086  end if
087  
088end repeat
089############
090#コピー先確保
091set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
092set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
093set strSetSubPath to ("Icons/AppIcon/" & ocidBaseDirName & "")
094set ocidSaveDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:(strSetSubPath) isDirectory:(true)
095#
096set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
097ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
098set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error| :(reference)
099############
100#コピー開始
101repeat with itemURL in ocidIcnsPathURLAllArray
102  #ファイル名
103  set ocidItemFileName to itemURL's lastPathComponent()
104  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidItemFileName) isDirectory:(false))
105  set listDone to (appFileManager's copyItemAtURL:(itemURL) toURL:(ocidSaveFilePathURL) |error| :(reference))
106  if (item 1 of listDone) is false then
107    set numCntDone to 1 as integer
108    #拡張子とって
109    set ocidBaseFileName to ocidItemFileName's stringByDeletingPathExtension()
110    #拡張子
111    set ocidItemExtensionName to ocidItemFileName's pathExtension()
112    repeat numCntRename times
113      set strSetNewFileName to ("" & ocidBaseFileName & " " & (numCntDone as text) & "." & ocidItemExtensionName & "") as text
114      set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSetNewFileName) isDirectory:(false))
115      set listDone to (appFileManager's copyItemAtURL:(itemURL) toURL:(ocidSaveFilePathURL) |error| :(reference))
116      if (item 1 of listDone) is true then
117        exit repeat
118      end if
119      set numCntDone to numCntDone + 1 as integer
120    end repeat
121  end if
122  
123end repeat
124
125#フォルダを開く
126set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
127set boolDone to appSharedWorkspace's openURL:(ocidSaveDirPathURL)
128
AppleScriptで生成しました

|

フォルダにアイコンセット(アイコンファイル指定)

こうなっちゃったのを
202502250224401_498x271_20250226140401
202502250225521_499x276_20250226140401
こうするだけの単機能
ですが
アイコンファイルを自分で追加すれば色々工夫できるようにしてあります


addicon2folder.zip

フォルダにアイコンセット.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# ループ処理にallObjectsを利用
005# 要管理者権限
006# アイコンデータが必要です
007(*   こちらからダウンロードしてください
008https://quicktimer.cocolog-nifty.com/icefloe/2025/02/post-8fa024.html
009*)
010#com.cocolog-nifty.quicktimer.icefloe
011----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
012##自分環境がos12なので2.8にしているだけです
013use AppleScript version "2.8"
014use framework "Foundation"
015use framework "AppKit"
016use scripting additions
017property refMe : a reference to current application
018#############################
019###ダイアログを前面に出す
020set strName to (name of current application) as text
021if strName is "osascript" then
022  tell application "SystemUIServer" to activate
023else
024  tell current application to activate
025end if
026############
027set appFileManager to refMe's NSFileManager's defaultManager()
028set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSApplicationDirectory) inDomains:(refMe's NSLocalDomainMask))
029set ocidApplicationDirPathURL to ocidURLsArray's firstObject()
030set aliasDefaultLocation to (ocidApplicationDirPathURL's absoluteURL()) as alias
031############
032set strMes to "フォルダを選んでください" as text
033set strPrompt to "アイコンをセットする\rフォルダを選択してください" as text
034try
035  tell application "SystemUIServer"
036    #Activateは必須
037    activate
038    set aliasDirPath to (choose folder strMes with prompt strPrompt default location aliasDefaultLocation with invisibles and showing package contents without multiple selections allowed) as alias
039  end tell
040on error
041  log "エラーしました"
042  return "エラーしました"
043end try
044############
045#パス
046set strDirPath to (POSIX path of aliasDirPath) as text
047set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
048set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
049set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
050#アイコンの入ったフォルダ
051set aliasPathToMe to (path to me) as alias
052set strPathToMe to (POSIX path of aliasPathToMe) as text
053set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)
054set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
055set ocidPathToMeURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:(false)
056set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent()
057set ocidMaterialDirPathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("Material") isDirectory:(true)
058#URLの収集
059set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
060set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
061ocidKeyArray's addObject:(refMe's NSURLPathKey)
062set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidMaterialDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
063set ocidSubPathURLArray to (item 1 of listResponse)
064set ocidIcnsFileNameArray to refMe's NSMutableArray's alloc()'s init()
065repeat with itemURL in ocidSubPathURLArray
066  set ocidFileName to itemURL's lastPathComponent()
067  (ocidIcnsFileNameArray's addObject:(ocidFileName))
068end repeat
069##ダイアログ
070set listIcnsFileName to ocidIcnsFileNameArray as list
071set strName to (name of current application) as text
072if strName is "osascript" then
073  tell application "SystemUIServer" to activate
074else
075  tell current application to activate
076end if
077set strTitle to ("選んでください") as text
078set strPrompt to ("アイコンをひとつ選んでください") as text
079try
080  tell application "SystemUIServer"
081    activate
082    set valueResponse to (choose from list listIcnsFileName with title strTitle with prompt strPrompt default items (item 2 of listIcnsFileName) OK button name "OK" cancel button name "キャンセル" with empty selection allowed without multiple selections allowed)
083  end tell
084on error
085  log "Error choose from list"
086  return false
087end try
088if (class of valueResponse) is boolean then
089  log "Error キャンセルしました"
090  return false
091else if (class of valueResponse) is list then
092  if valueResponse is {} then
093    log "Error 何も選んでいません"
094    return false
095  else
096    set strResponse to (item 1 of valueResponse) as text
097  end if
098end if
099#セットするアイコンパス
100set strIconFileName to strResponse as text
101set ocidSetIconFilePathURL to ocidMaterialDirPathURL's URLByAppendingPathComponent:(strIconFileName) isDirectory:(false)
102#アイコンデータ読み込み NSDATA
103set ocidOption to (refMe's NSDataReadingMappedIfSafe)
104set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidSetIconFilePathURL) options:(ocidOption) |error| :(reference)
105set ocidIconData to (item 1 of listResponse)
106#NSIMAGE
107set ocidIconImage to refMe's NSImage's alloc()'s initWithData:(ocidIconData)
108#アイコンセット
109set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
110set ocidOption to (refMe's NSExclude10_4ElementsIconCreationOption)
111set boolDone to (appSharedWorkspace's setIcon:(ocidIconImage) forFile:(ocidDirPath) options:(ocidOption))
112if boolDone is false then
113#念の為アクセス権を変更しておく
114set strDirPath to ocidDirPath as text
115#アクセス権で付与できない場合
116log doZshShellScriptSudo("/usr/bin/chgrp admin \"" & strDirPath & "\"")
117set boolDone to (appSharedWorkspace's setIcon:(ocidIconImage) forFile:(ocidDirPath) options:(ocidOption))
118end if
119
120
121##########################
122# 【SUDO】ZSH 実行
123to doZshShellScriptSudo(argCommandText)
124  set strCommandText to argCommandText as text
125  log "\r" & strCommandText & "\r"
126  set strExec to ("/bin/zsh -c '/usr/bin/sudo " & strCommandText & "'") as text
127  ##########
128  #コマンド実行
129  try
130    log "コマンド開始"
131    set strResnponse to (do shell script strExec) as text
132    log "コマンド終了"
133  on error
134    return {false, strResnponse}
135  end try
136  return {true, strResnponse}
137end doZshShellScriptSudo
AppleScriptで生成しました

|

[ICON]エイリアスに参照元のアイコンデータを付与する(矢印のバッチ付与)

エイリアスに元のアイコンを付与する矢印付.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004# 
005#  エイリアスファイルをFinder上で選択した状態から実行
006# 矢印バッチ付きのアイコンを合成してからペーストする
007# あくまでも アイコンデータを取得する QuickLookデータではない
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009use AppleScript version "2.8"
010use framework "Foundation"
011use framework "AppKit"
012use framework "UniformTypeIdentifiers"
013use scripting additions
014property refMe : a reference to current application
015set appFileManager to refMe's NSFileManager's defaultManager()
016
017
018#############################
019#Finderで選択したエイリアスを処理
020tell application "Finder"
021  set listSelectedObject to (get selection as alias list) as list
022end tell
023repeat with itemAliasFilePath in listSelectedObject
024  set aliasSourceFilePath to itemAliasFilePath as alias
025  #エイリアスファイルなら処理する
026  set recordFileInfo to get info for aliasSourceFilePath
027  if (type identifier of recordFileInfo) is "com.apple.alias-file" then
028    #パス
029    set strSourceFilePath to (POSIX path of aliasSourceFilePath) as text
030    set ocidSourceFilePathStr to (refMe's NSString's stringWithString:(strSourceFilePath))
031    set ocidSourceFilePath to ocidSourceFilePathStr's stringByStandardizingPath()
032    set ocidSourceFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSourceFilePath) isDirectory:(false))
033    #参照先のURLのbookmarkDATAを取得
034    set listResponse to (refMe's NSURL's bookmarkDataWithContentsOfURL:(ocidSourceFilePathURL) |error| :(reference))
035    set ocdiBookMarkData to (item 1 of listResponse)
036    #BOOKMARKデータから参照先のURLを取得
037    set ocidOption to (refMe's NSURLBookmarkResolutionWithoutUI)
038    set listResponse to (refMe's NSURL's URLByResolvingBookmarkData:(ocdiBookMarkData) options:(ocidOption) relativeToURL:(missing value) bookmarkDataIsStale:(true) |error| :(reference))
039    set ocidResolvedURL to (item 1 of listResponse)
040    set ocidResolvedFilePath to ocidResolvedURL's |path|() as text
041    #アイコンデータ取り出し
042    set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
043    set ocidIconImageData to (appSharedWorkspace's iconForFile:(ocidResolvedFilePath))
044    set ocidSetIconImage to doSetBadge2Icon(ocidIconImageData)
045    
046    #アイコン付与
047    set ocidOption to (refMe's NSExclude10_4ElementsIconCreationOption)
048    set boolDone to (appSharedWorkspace's setIcon:(ocidSetIconImage) forFile:(ocidSourceFilePath) options:(ocidOption))
049  else
050    log "エイリアスファイル以外は処理しない"
051  end if
052  
053end repeat
054
055return
056
057to doSetBadge2Icon(argIconImageData)
058  #PTサイズ
059  #32pxと小サイズなのでサイズ使わないことにした
060  # set ocidPtSize to argIconImageData's |size|()
061  # set ocidPointHigh to ocidPtSize's width()
062  # set ocidPontWide to ocidPtSize's height()
063  # log ocidPontWide as number
064  #PXサイズ
065  # set ocidIconRepArray to ocidIconImageData's representations()
066  # set ocidIconImageRep to ocidIconRepArray's firstObject()
067  set ocidTffRep to argIconImageData's TIFFRepresentation()
068  set ocidIconImageRep to refMe's NSBitmapImageRep's alloc()'s initWithData:(ocidTffRep)
069  #32pxと小サイズなのでサイズ使わないことにした
070  # set ocidIconPixelsHigh to ocidIconImageRep's pixelsHigh()
071  # set ocidIconPixelsWide to ocidIconImageRep's pixelsWide()
072  # set strPixelsWide to ocidIconPixelsWide as text
073  #あとで使う
074  # set recordIconNo2Size to {|0|:"1024", |1|:"512", |3|:"256", |5|:"128", |6|:"62", |7|:"32", |9|:"16"} as record
075  # set recordIconSize2NO to {|1024|:0, |512|:1, |256|:3, |128|:5, |62|:6, |32|:7, |16|:9} as record
076  #レコードにして
077  # set ocidSizeDict to refMe's NSMutableDictionary's alloc()'s init()
078  # ocidSizeDict's setDictionary:(recordIconSize2NO)
079  #ピクセルサイズでArrayの番号を取得
080  #set numSizePos to ocidSizeDict's valueForKey:(strPixelsWide)
081  
082  #結局矢印のバッチのサイズに合わせて拡大ペーストすることにした
083  set ocidIconPixelsHigh to 1024
084  set ocidIconPixelsWide to 1024
085  set numSizePos to 0
086  
087  #エイリアスの合成画像
088  set appFileManager to refMe's NSFileManager's defaultManager()
089  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSCoreServiceDirectory) inDomains:(refMe's NSSystemDomainMask))
090  set ocidCoreServiceDirPathURL to ocidURLsArray's firstObject()
091  set ocidBadgeIconFilePathURL to ocidCoreServiceDirPathURL's URLByAppendingPathComponent:("CoreTypes.bundle/Contents/Resources/AliasBadgeIcon.icns") isDirectory:(false)
092  #NSDATA
093  set ocidOption to (refMe's NSDataReadingMappedIfSafe)
094  set listResponse to (refMe's NSData's alloc()'s initWithContentsOfURL:(ocidBadgeIconFilePathURL) options:(ocidOption) |error| :(reference))
095  set ocidBadgeIconData to (item 1 of listResponse)
096  #NSIMAGE
097  set ocidBadgemage to (refMe's NSImage's alloc()'s initWithData:(ocidBadgeIconData))
098  #set ocidBadgePtSize to ocidBadgemage's |size|()
099  #set ocidBadgePointHigh to ocidBadgePtSize's width()
100  #set ocidBadgePontWide to ocidBadgePtSize's height()
101  set ocidBadgeRepArray to ocidBadgemage's representations()
102  set ocidBadgeImageRep to ocidBadgeRepArray's objectAtIndex:(numSizePos)
103  #set ocidBadgePixelsHigh to ocidBadgeImageRep's pixelsHigh()
104  #set ocidBadgePixelsWide to ocidBadgeImageRep's pixelsWide()
105  
106  ###########################
107  #【1】背景部
108  #セットするRECT
109  set ocidDrawRect to refMe's NSRect's NSMakeRect(0, 0, ocidIconPixelsWide, ocidIconPixelsHigh)
110  # RGB系のカラースペース
111  set ocidColorSpaceName to (refMe's NSCalibratedRGBColorSpace)
112  # アルファあり
113  set ocidBitmapFormat to (refMe's NSAlphaFirstBitmapFormat)
114  #アートボード
115  set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(ocidIconPixelsWide) pixelsHigh:(ocidIconPixelsHigh) bitsPerSample:(8) samplesPerPixel:(4) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(0) bitsPerPixel:(32))
116  #カラーを定義 背景色透過
117  set ocidBackgroundColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(0))
118  
119  ####【NSGraphicsContext's】
120  refMe's NSGraphicsContext's saveGraphicsState()
121  #Context 選択した画像を読み込んで
122  set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
123  (ocidSetImageContext's setShouldAntialias:(true))
124  (ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
125  (ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
126  #生成された画像でNSGraphicsContext初期化
127  (refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
128  #RGB値で背景色をセットして
129  ocidBackgroundColor's |set|()
130  #指定した色で背景を塗る
131  refMe's NSRectFill(ocidDrawRect)
132  #処理終了
133  refMe's NSGraphicsContext's restoreGraphicsState()
134  ####【NSGraphicsContext's】
135  
136  
137  ###########################
138  #【2】アイコン部
139  ####【NSGraphicsContext's】
140  refMe's NSGraphicsContext's saveGraphicsState()
141  #Context 選択した画像を読み込んで
142  set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
143  (ocidSetImageContext's setShouldAntialias:(true))
144  (ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
145  (ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
146  #1で生成された画像でNSGraphicsContext初期化
147  (refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
148  #画像をペースト
149  set ocidCopyRect to refMe's NSZeroRect
150  set ocidPasteRect to refMe's NSRect's NSMakeRect(0, 0, ocidIconPixelsWide, ocidIconPixelsHigh)
151  (ocidIconImageRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
152  #処理終了
153  refMe's NSGraphicsContext's restoreGraphicsState()
154  ####【NSGraphicsContext's】
155  
156  ###########################
157  #【3】バッチ部
158  ####【NSGraphicsContext's】
159  refMe's NSGraphicsContext's saveGraphicsState()
160  #Context 選択した画像を読み込んで
161  set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
162  (ocidSetImageContext's setShouldAntialias:(true))
163  (ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
164  (ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
165  #1で生成された画像でNSGraphicsContext初期化
166  (refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
167  #画像をペースト
168  set ocidCopyRect to refMe's NSZeroRect
169  set ocidPasteRect to refMe's NSRect's NSMakeRect(0, 0, ocidIconPixelsWide, ocidIconPixelsHigh)
170  (ocidBadgeImageRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
171  #処理終了
172  refMe's NSGraphicsContext's restoreGraphicsState()
173  ####【NSGraphicsContext's】
174  
175  ###########################
176  #NSIMAGEを戻す
177  set ocidSetSize to refMe's NSSize's NSMakeSize(ocidIconPixelsWide, ocidIconPixelsHigh)
178  ocidArtBoardRep's setSize:(ocidSetSize)
179  set ocidSaveImage to refMe's NSImage's alloc()'s initWithSize:(ocidSetSize)
180  ocidSaveImage's addRepresentation:(ocidArtBoardRep)
181  return ocidSaveImage
182  
183end doSetBadge2Icon
AppleScriptで生成しました

|

[ICON]エイリアスに参照元のアイコンデータを付与する

エイリアスに元のアイコンを付与する.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#  エイリアスファイルをFinder上で選択した状態から実行
005# あくまでも アイコンデータを取得する QuickLookデータではない
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use framework "UniformTypeIdentifiers"
011use scripting additions
012property refMe : a reference to current application
013set appFileManager to refMe's NSFileManager's defaultManager()
014
015
016#############################
017#Finderで選択したエイリアスを処理
018tell application "Finder"
019  set listSelectedObject to (get selection as alias list) as list
020end tell
021repeat with itemAliasFilePath in listSelectedObject
022  set aliasSourceFilePath to itemAliasFilePath as alias
023  #エイリアスファイルなら処理する
024  set recordFileInfo to get info for aliasSourceFilePath
025  if (type identifier of recordFileInfo) is "com.apple.alias-file" then
026    #パス
027    set strSourceFilePath to (POSIX path of aliasSourceFilePath) as text
028    set ocidSourceFilePathStr to (refMe's NSString's stringWithString:(strSourceFilePath))
029    set ocidSourceFilePath to ocidSourceFilePathStr's stringByStandardizingPath()
030    set ocidSourceFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSourceFilePath) isDirectory:(false))
031    #参照先のURLのbookmarkDATAを取得
032    set listResponse to (refMe's NSURL's bookmarkDataWithContentsOfURL:(ocidSourceFilePathURL) |error| :(reference))
033    set ocdiBookMarkData to (item 1 of listResponse)
034    #BOOKMARKデータから参照先のURLを取得
035    set ocidOption to (refMe's NSURLBookmarkResolutionWithoutUI)
036    set listResponse to (refMe's NSURL's URLByResolvingBookmarkData:(ocdiBookMarkData) options:(ocidOption) relativeToURL:(missing value) bookmarkDataIsStale:(true) |error| :(reference))
037    set ocidResolvedURL to (item 1 of listResponse)
038    set ocidResolvedFilePath to ocidResolvedURL's |path|() as text
039    #アイコンデータ取り出し
040    set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
041    set ocidIconImageData to (appSharedWorkspace's iconForFile:(ocidResolvedFilePath))
042    #アイコン付与
043    set ocidOption to (refMe's NSExclude10_4ElementsIconCreationOption)
044    set boolDone to (appSharedWorkspace's setIcon:(ocidIconImageData) forFile:(ocidSourceFilePath) options:(ocidOption))
045  else
046    log "エイリアスファイル以外は処理しない"
047  end if
048  
049end repeat
050
051return
AppleScriptで生成しました

|

[dscl]ユーザーアイコン画像の取り出し


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# ユーザーアカウントの画像を取り出す
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010
011property refMe : a reference to current application
012
013
014##########################
015#ユーザーリスト
016set strCommandText to ("/usr/bin/dscl . list /Users") as text
017set strResponse to doZshShellScript(strCommandText) as text
018#
019set ocidResponseStrings to refMe's NSString's stringWithString:(strResponse)
020set ocidResponseStrings to (ocidResponseStrings's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
021set ocidResponseStrings to (ocidResponseStrings's stringByReplacingOccurrencesOfString:("\n\n") withString:("\n"))
022set ocidUidArray to ocidResponseStrings's componentsSeparatedByString:("\n")
023#特定のユーザーを除外
024ocidUidArray's removeObject:("root")
025ocidUidArray's removeObject:("nobody")
026ocidUidArray's removeObject:("daemon")
027ocidUidArray's removeObject:("macports")
028# ユーザー名が『_ アンダースコア』からはじまるユーザーを除外
029set appPredicate to refMe's NSPredicate's predicateWithFormat:("NOT (SELF BEGINSWITH '_')")
030ocidUidArray's filterUsingPredicate:(appPredicate)
031
032log ocidUidArray as list
033
034##########################
035#保存先
036set appFileManager to refMe's NSFileManager's defaultManager()
037set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
038set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
039set ocidSavePreDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/UserIcon") isDirectory:(true)
040#フォルダアクセス権
041set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
042ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
043
044##########################
045#処理
046repeat with itemUID in ocidUidArray
047  set ocidSaveDirPathURL to (ocidSavePreDirPathURL's URLByAppendingPathComponent:(itemUID) isDirectory:(true))
048  set ocidSaveTextPathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:("JPEGPhoto.hex.bin") isDirectory:(false))
049  set strSaveTextPath to ocidSaveTextPathURL's |path|() as text
050  
051  #
052  set listDone to (appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference))
053  #書き出して
054  set strCommandText to ("/usr/bin/dscl . read /Users/" & itemUID & " JPEGPhoto > \"" & strSaveTextPath & "\"") as text
055  set strResponse to doZshShellScript(strCommandText) as text
056  if strResponse is false then
057    return "データ書き出し失敗"
058  end if
059  #拡張子判定
060  set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidSaveTextPathURL) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
061  set ocidReadStrings to (item 1 of listResponse)
062  #
063  set ocidReadStrings to (ocidReadStrings's stringByReplacingOccurrencesOfString:("JPEGPhoto:\n ") withString:(""))
064  #色々設定してみたものの たぶんjpeg か tiffのみと思われる
065  set boolJpeg to (ocidReadStrings's hasPrefix:("ffd8ff")) as boolean
066  set boolIconsT to (ocidReadStrings's hasPrefix:("4d4d002a")) as boolean
067  set boolIconsB to (ocidReadStrings's hasPrefix:("00000100")) as boolean
068  set boolPng to (ocidReadStrings's hasPrefix:("89504e47")) as boolean
069  set boolTifB to (ocidReadStrings's hasPrefix:("4d4d002a")) as boolean
070  set boolTifL to (ocidReadStrings's hasPrefix:("49492a00")) as boolean
071  set boolGif to (ocidReadStrings's hasPrefix:("47494638")) as boolean
072  set boolBmp to (ocidReadStrings's hasPrefix:("424d")) as boolean
073  set boolHeic to (ocidReadStrings's containsString:("66747970 68656963")) as boolean
074  if boolJpeg is true then
075    set strSaveFileName to ("JPEGPhoto.jpg") as text
076  else if boolIconsT is true then
077    set strSaveFileName to ("JPEGPhoto.tif") as text
078  else if boolIconsB is true then
079    set strSaveFileName to ("JPEGPhoto.icns") as text
080  else if boolHeic is true then
081    set strSaveFileName to ("JPEGPhoto.heic") as text
082  else if boolPng is true then
083    set strSaveFileName to ("JPEGPhoto.png") as text
084  else if boolTifB is true then
085    set strSaveFileName to ("JPEGPhoto.tif") as text
086  else if boolTifL is true then
087    set strSaveFileName to ("JPEGPhoto.tiff") as text
088  else if boolGif is true then
089    set strSaveFileName to ("JPEGPhoto.gif") as text
090  else if boolBmp is true then
091    set strSaveFileName to ("JPEGPhoto.bmp") as text
092  end if
093  set ocidSaveImagePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
094  set strSaveImagePath to ocidSaveImagePathURL's |path|() as text
095  #変換
096  set strCommandText to ("/usr/bin/xxd -r -p  \"" & strSaveTextPath & "\" \"" & strSaveImagePath & "\"") as text
097  set strResponse to doZshShellScript(strCommandText) as text
098  if strResponse is false then
099    return "データ書き出し失敗"
100  end if
101  #テキストをゴミ箱へ
102  set listDone to (appFileManager's trashItemAtURL:(ocidSaveTextPathURL) resultingItemURL:(ocidSaveTextPathURL) |error| :(reference))
103  
104end repeat
105
106
107#保存先を開く
108set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
109set boolDone to appSharedWorkspace's openURL:(ocidSavePreDirPathURL)
110
111
112
113##########################
114# 【N】ZSH 実行
115to doZshShellScript(argCommandText)
116  set strCommandText to argCommandText as text
117  log "コマンド開始\r" & strCommandText & "\r"
118  set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
119  ##########
120  #コマンド実行
121  try
122    set strResnponse to (do shell script strExec) as text
123    log "コマンド終了"
124  on error
125    return false
126  end try
127  return strResnponse
128end doZshShellScript
AppleScriptで生成しました

|

[icns]ファイルのアイコンを選んだ画像にする


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.6"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010
011property refMe : a reference to current application
012###初期化
013set appFileManager to refMe's NSFileManager's defaultManager()
014set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
015
016##############################
017#####入力ファイル ダイアログ
018##############################
019tell current application
020  set strName to name as text
021end tell
022####スクリプトメニューから実行したら
023if strName is "osascript" then
024  tell application "Finder" to activate
025else
026  tell current application to activate
027end if
028###デスクトップ
029set ocidDesktopPathArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
030set ocidDesktopPathURL to ocidDesktopPathArray's firstObject()
031set alisDesktopPath to (ocidDesktopPathURL's absoluteURL()) as alias
032###ダイアログ
033set listUTI to {"public.item"}
034set strMes to ("ファイルを選んでください") as text
035set strPrompt to ("ファイルを選んでください") as text
036try
037  ### ファイル選択時
038  set aliasFilePath to (choose file strMes with prompt strPrompt default location (alisDesktopPath) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
039on error
040  log "エラーしました"
041  return
042end try
043##########
044set strFilePath to (POSIX path of aliasFilePath) as text
045set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
046set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
047set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
048
049##############################
050#####アイコンファイル ダイアログ
051##############################
052tell current application
053  set strName to name as text
054end tell
055####スクリプトメニューから実行したら
056if strName is "osascript" then
057  tell application "Finder" to activate
058else
059  tell current application to activate
060end if
061###デスクトップ
062set appFileManager to refMe's NSFileManager's defaultManager()
063set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
064set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
065set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
066###ダイアログ
067set listUTI to {"public.image"}
068set strMes to ("画像ファイルを選んでください") as text
069set strPrompt to ("画像ファイルを選んでください") as text
070try
071  ### ファイル選択時
072  set aliasImageFilePath to (choose file strMes with prompt strPrompt default location (aliasDesktopDirPath) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
073on error
074  log "エラーしました"
075  return
076end try
077##########
078set strImageFilePath to (POSIX path of aliasImageFilePath) as text
079set ocidImageFilePathStr to refMe's NSString's stringWithString:(strImageFilePath)
080set ocidImageFilePath to ocidImageFilePathStr's stringByStandardizingPath()
081set ocidImageFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidImageFilePath) isDirectory:false)
082
083#NSDATA
084set ocidOption to (refMe's NSDataReadingMappedIfSafe)
085set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidImageFilePathURL) options:(ocidOption) |error| :(reference)
086set ocidReadSetData to (item 1 of listResponse)
087
088#NSIMAGE
089set ocidSetImage to refMe's NSImage's alloc()'s initWithData:(ocidReadSetData)
090
091###アイコン付与
092set boolAddIcon to (appSharedWorkspace's setIcon:(ocidSetImage) forFile:(ocidFilePath) options:(refMe's NSExclude10_4ElementsIconCreationOption))
093
094return 0
AppleScriptで生成しました

|

[Icns]耳折れドキュメントアイコンを合成するv2(解像度違いに対応)

こんな感じのアイコンを作成します
Icon_40x402x


ダウンロード - dociconv2.zip




AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# 横長のイメージの合成には向かない
005# v2 読み込む画像の解像度の違いに対応した仮版
006(*
007A:ドキュメントアイコンに画像を合成したPNG画像生成
008B:ICONSET用の各サイズ画像を生成
009C:ICNSを作成
010
011ドキュメント画像合成
0121:合成する画像を読み込み
0132:アートボード 背景
0143:ドキュメント部
0154:合成する読み込み画像
0165:グラデーション
0176:折れ耳部
0187:ドロップシャドウ
019
020画像素材が必要です
021こちら
022https://quicktimer.cocolog-nifty.com/icefloe/files/dociconv2.zip
023
024ダウンロードして利用してください
025
026*)
027#com.cocolog-nifty.quicktimer.icefloe
028----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
029use AppleScript version "2.8"
030use framework "Foundation"
031use framework "UniformTypeIdentifiers"
032use framework "AppKit"
033#use framework "Carbon"
034use scripting additions
035property refMe : a reference to current application
036
037
038set appFileManager to refMe's NSFileManager's defaultManager()
039
040#ダイアログ
041set strName to (name of current application) as text
042if strName is "osascript" then
043  tell application "Finder" to activate
044else
045  tell current application to activate
046end if
047set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
048set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
049set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
050
051set listUTI to {"public.image"}
052set strMes to ("画像ファイルを選んでください") as text
053set strPrompt to ("画像ファイルを選んでください") as text
054try
055  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
056on error
057  log "エラーしました"
058  return "エラーしました"
059end try
060#入力ファイルパス
061set strInsFilePath to (POSIX path of aliasFilePath) as text
062set ocidInsFilePathStr to refMe's NSString's stringWithString:(strInsFilePath)
063set ocidInsFilePath to ocidInsFilePathStr's stringByStandardizingPath
064set ocidInsFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidInsFilePath) isDirectory:(false)
065
066#####
067#出力イメージサイズ
068set numW to (1024) as integer
069set numH to (1024) as integer
070#################
071#画像生成開始
072#カラーICC
073set strIccFilePath to ("/System/Library/ColorSync/Profiles/sRGB Profile.icc") as text
074set ocidIccFilePathStr to refMe's NSString's stringWithString:(strIccFilePath)
075set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
076set ocidIccFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidIccFilePath) isDirectory:(false)
077set ocidProfileData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidIccFilePathURL)
078#セットするRECT
079set ocidDrawRect to refMe's NSRect's NSMakeRect(0, 0, numW, numH)
080# RGB系のカラースペース
081set ocidColorSpaceName to (refMe's NSCalibratedRGBColorSpace)
082# アルファあり
083set ocidBitmapFormat to (refMe's NSAlphaFirstBitmapFormat)
084#アートボード
085set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numW) pixelsHigh:(numH) bitsPerSample:(8) samplesPerPixel:(4) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(0) bitsPerPixel:(32))
086#カラーを定義 背景色透過
087set ocidBackgroundColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(0))
088
089###########################
090#【1】背景部
091####【NSGraphicsContext's】
092refMe's NSGraphicsContext's saveGraphicsState()
093#Context 選択した画像を読み込んで
094set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
095(ocidSetImageContext's setShouldAntialias:(true))
096(ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
097(ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
098#生成された画像でNSGraphicsContext初期化
099(refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
100#RGB値で背景色をセットして
101ocidBackgroundColor's |set|()
102#指定した色で背景を塗る
103refMe's NSRectFill(ocidDrawRect)
104#処理終了
105refMe's NSGraphicsContext's restoreGraphicsState()
106####【NSGraphicsContext's】
107
108###########################
109#【2】ドキュメント部分
110set numDocPxW to 688 as integer
111set numDocPxH to 908 as integer
112#
113set aliasPathToMe to (path to me) as alias
114set strPathToMe to (POSIX path of aliasPathToMe) as text
115set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)
116set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
117set ocidContainerDirPath to ocidPathToMe's stringByDeletingLastPathComponent()
118set ocidGradationFilePath to ocidContainerDirPath's stringByAppendingPathComponent:("Material/icon_512x512@2x@2x.png")
119#NSDATA
120set ocidOption to (refMe's NSDataReadingMappedIfSafe)
121set listResponse to refMe's NSData's alloc()'s initWithContentsOfFile:(ocidGradationFilePath) options:(ocidOption) |error| :(reference)
122set ocidReadData to (item 1 of listResponse)
123#NSIMAGE
124set ocidGradationImage to refMe's NSImage's alloc()'s initWithData:(ocidReadData)
125#IMAGEREP
126set ocidTffRep to ocidGradationImage's TIFFRepresentation()
127set ocidGradationRep to refMe's NSBitmapImageRep's alloc()'s initWithData:(ocidTffRep)
128#ドキュメントの背景色 白 透過無し
129set ocidDocColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(1))
130set ocidDocRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numDocPxW) pixelsHigh:(numDocPxH) bitsPerSample:(8) samplesPerPixel:(4) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(0) bitsPerPixel:(32))
131
132####【NSGraphicsContext's】
133refMe's NSGraphicsContext's saveGraphicsState()
134#Context 選択した画像を読み込んで
135set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidDocRep))
136(ocidSetImageContext's setShouldAntialias:(true))
137(ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
138(ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
139#1で生成された画像でNSGraphicsContext初期化
140(refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
141#外側の角丸のマスク
142set ocidMaskRect to refMe's NSRect's NSMakeRect(0, 0, numDocPxW, numDocPxH)
143set ocidMaskPath to refMe's NSBezierPath's bezierPathWithRoundedRect:(ocidMaskRect) xRadius:(20) yRadius:(20)
144ocidMaskPath's addClip()
145#RGB値で背景色をセットして
146ocidDocColor's |set|()
147#指定した色で背景を塗る
148refMe's NSRectFill(ocidDrawRect)
149
150#外側の角丸のマスク
151set ocidMaskRect to refMe's NSRect's NSMakeRect(0, 0, numDocPxW, numDocPxH)
152set ocidMaskPath to refMe's NSBezierPath's bezierPathWithRoundedRect:(ocidMaskRect) xRadius:(20) yRadius:(20)
153ocidMaskPath's addClip()
154#処理終了
155refMe's NSGraphicsContext's restoreGraphicsState()
156####【NSGraphicsContext's】
157
158
159###########################
160#【3】【1】の上に【2】をペースト
161#耳折れのマスクイメージを読み込む
162set ocidMaskFilePath to ocidContainerDirPath's stringByAppendingPathComponent:("Material/Fold_Mask_icon 512@2X@2x.png")
163#NSDATA
164set ocidOption to (refMe's NSDataReadingMappedIfSafe)
165set listResponse to refMe's NSData's alloc()'s initWithContentsOfFile:(ocidMaskFilePath) options:(ocidOption) |error| :(reference)
166set ocidReadData to (item 1 of listResponse)
167#NSIMAGE
168set ocidMaskImage to refMe's NSImage's alloc()'s initWithData:(ocidReadData)
169#IMAGEREP
170set ocidTffRep to ocidMaskImage's TIFFRepresentation()
171set ocidMaskRep to refMe's NSBitmapImageRep's alloc()'s initWithData:(ocidTffRep)
172set ocidImageMaskRect to refMe's NSRect's NSMakeRect(476, 586, 380, 380)
173
174####【NSGraphicsContext's】
175refMe's NSGraphicsContext's saveGraphicsState()
176#Context 選択した画像を読み込んで
177set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
178(ocidSetImageContext's setShouldAntialias:(true))
179(ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
180(ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
181#生成された画像でNSGraphicsContext初期化
182(refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
183
184#画像をペースト
185set ocidCopyRect to refMe's NSZeroRect
186set ocidPasteRect to refMe's NSRect's NSMakeRect(168, 58, numDocPxW, numDocPxH)
187(ocidDocRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
188
189#マスクを指定
190set ocidCopyRect to refMe's NSZeroRect
191set ocidPasteRect to refMe's NSRect's NSMakeRect(168, 58, numDocPxW, numDocPxH)
192ocidMaskRep's drawInRect:(ocidImageMaskRect)
193(ocidMaskRep's drawInRect:(ocidImageMaskRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationDestinationOver) fraction:(1.0) respectFlipped:(true) hints:(missing value))
194
195#抜けた場所用に上からペースト
196set ocidCopyRect to refMe's NSZeroRect
197set ocidPasteRect to refMe's NSRect's NSMakeRect(168, 58, numDocPxW, numDocPxH)
198(ocidDocRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceAtop) fraction:(1.0) respectFlipped:(false) hints:(missing value))
199#処理終了
200refMe's NSGraphicsContext's restoreGraphicsState()
201####【NSGraphicsContext's】
202#REP確定
203set ocidDrawRect to refMe's NSRect's NSMakeRect(0, 0, numW, numH)
204ocidArtBoardRep's drawInRect:(ocidDrawRect)
205
206###########################
207#【4】合成するアイコン画像
208#NSDATA
209set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidInsFilePathURL) options:(ocidOption) |error| :(reference)
210set ocidReadSetData to (item 1 of listResponse)
211#NSIMAGE
212set ocidSetImage to refMe's NSImage's alloc()'s initWithData:(ocidReadSetData)
213(*
214set ocidSetImageSize to ocidSetImage's |size|()
215set numSetImagePtWidth to ocidSetImageSize's width()
216set numSetImagePtHeight to ocidSetImageSize's height()
217*)
218#IMAGEREP
219set ocidTffRep to ocidSetImage's TIFFRepresentation()
220set ocidSetImageRep to refMe's NSBitmapImageRep's alloc()'s initWithData:(ocidTffRep)
221set numSetImagePixelsWidth to ocidSetImageRep's pixelsWide()
222set numSetImagePixelsHeight to ocidSetImageRep's pixelsHigh()
223#解像度 縦横
224(*
225set SetImageResolutionW to (numSetImagePixelsWidth / numSetImagePtWidth) as number
226set SetImageResolutionH to (numSetImagePixelsHeight / numSetImagePtHeight) as number
227*)
228
229set ocidImageInsRect to refMe's NSRect's NSMakeRect(0, 0, 520, 600)
230#サイズ計算 幅 縦 
231if numSetImagePixelsWidth > numSetImagePixelsHeight then
232  set numRatio to (numSetImagePixelsHeight / numSetImagePixelsWidth) as number
233  set numDiffW to (520 - numSetImagePixelsWidth)
234  set numSetW to (numSetImagePixelsWidth + numDiffW) as integer
235  set numSetH to (numSetW * numRatio) as integer
236  set numDiffH to (600 - numSetH) as integer
237else if numSetImagePixelsWidth < numSetImagePixelsHeight then
238  set numRatio to (numSetImagePixelsWidth / numSetImagePixelsHeight) as number
239  set numDiffH to (600 - numSetImagePixelsHeight) as number
240  set numSetH to (numSetImagePixelsHeight + numDiffH) as integer
241  set numSetW to (numSetH * numRatio) as integer
242  set numDiffW to (520 - numSetW) as integer
243else if numSetImagePixelsWidth = numSetImagePixelsHeight then
244  set numRatio to 1 as number
245  set numSetH to (600) as integer
246  set numSetW to (600) as integer
247end if
248#最終的なDRAWRECTを計算
249set numPasteX to ((numW - numSetW) / 2) as integer
250set numPasteY to ((numH - numSetH) / 2) as integer
251(*
252set numSetW to (numSetW * SetImageResolutionW) as number
253set numSetH to (numSetH * SetImageResolutionH) as number
254*)
255
256####【NSGraphicsContext's】
257refMe's NSGraphicsContext's saveGraphicsState()
258#Context 選択した画像を読み込んで
259set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
260(ocidSetImageContext's setShouldAntialias:(true))
261(ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
262(ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
263#生成された画像でNSGraphicsContext初期化
264(refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
265#マスクかけてから
266set ocidCopyRect to refMe's NSZeroRect
267set ocidPasteRect to refMe's NSRect's NSMakeRect(168, 58, numDocPxW, numDocPxH)
268
269ocidMaskRep's drawInRect:(ocidImageMaskRect)
270(ocidMaskRep's drawInRect:(ocidImageMaskRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationDestinationOver) fraction:(1.0) respectFlipped:(true) hints:(missing value))
271#上からペースト再ペースト
272set ocidCopyRect to refMe's NSZeroRect
273set ocidPasteRect to refMe's NSRect's NSMakeRect(168, 58, numDocPxW, numDocPxH)
274
275(ocidDocRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceAtop) fraction:(1.0) respectFlipped:(false) hints:(missing value))
276#合成画像も上から再ペースト
277# set ocidCopyRect to refMe's NSRect's NSMakeRect(0, 0, numSetImagePixelsWidth, numSetImagePixelsHeight)
278set ocidCopyRect to refMe's NSZeroRect
279set ocidPasteRect to refMe's NSRect's NSMakeRect(numPasteX, numPasteY, numSetW, numSetH)
280(ocidSetImageRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceAtop) fraction:(1) respectFlipped:(false) hints:(missing value))
281
282#グラデーションをペースト
283set ocidCopyRect to refMe's NSZeroRect
284set ocidPasteRect to refMe's NSRect's NSMakeRect(0, 0, numW, numH)
285(ocidGradationRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(0.5) respectFlipped:(false) hints:(missing value))
286
287#処理終了
288refMe's NSGraphicsContext's restoreGraphicsState()
289####【NSGraphicsContext's】
290
291
292###########################
293#【5】耳折れ上部をペースト
294set ocidFoldShadowFilePath to ocidContainerDirPath's stringByAppendingPathComponent:("Material/Fold_Shadow_icon 512@2X@2x.png")
295#NSDATA
296set ocidOption to (refMe's NSDataReadingMappedIfSafe)
297set listResponse to refMe's NSData's alloc()'s initWithContentsOfFile:(ocidFoldShadowFilePath) options:(ocidOption) |error| :(reference)
298set ocidReadData to (item 1 of listResponse)
299#NSIMAGE
300set ocidFoldShadowImage to refMe's NSImage's alloc()'s initWithData:(ocidReadData)
301#IMAGEREP
302set ocidTffRep to ocidFoldShadowImage's TIFFRepresentation()
303set ocidFoldShadowRep to refMe's NSBitmapImageRep's alloc()'s initWithData:(ocidTffRep)
304#コピー位置
305set ocidCopyRect to refMe's NSZeroRect
306set ocidPasteRect to refMe's NSRect's NSMakeRect(477, 585, 380, 380)
307
308####【NSGraphicsContext's】
309refMe's NSGraphicsContext's saveGraphicsState()
310#Context 選択した画像を読み込んで
311set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
312(ocidSetImageContext's setShouldAntialias:(true))
313(ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
314(ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
315#生成された画像でNSGraphicsContext初期化
316(refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
317#ペースト
318(ocidFoldShadowRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
319
320#処理終了
321refMe's NSGraphicsContext's restoreGraphicsState()
322####【NSGraphicsContext's】
323
324###########################
325#【6】シャドウ
326#ドロップシャドウ初期化
327set ocidSetShadow to refMe's NSShadow's alloc()'s init()
328set ocidOffSetSize to refMe's NSSize's NSMakeSize(0, 0)
329ocidSetShadow's setShadowOffset:(ocidOffSetSize)
330ocidSetShadow's setShadowBlurRadius:(20)
331set ocidShadowColor to refMe's NSColor's colorWithCalibratedWhite:(0) alpha:(0.4)
332ocidSetShadow's setShadowColor:(ocidShadowColor)
333#SaveImage
334set ocidSaveImageRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numW) pixelsHigh:(numH) bitsPerSample:(8) samplesPerPixel:(4) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(0) bitsPerPixel:(32))
335#
336#カラーを定義
337set ocidSaveImageColor to (refMe's NSColor's colorWithSRGBRed:(1) green:(1) blue:(1) alpha:(0))
338
339####【NSGraphicsContext's】
340refMe's NSGraphicsContext's saveGraphicsState()
341#Context 選択した画像を読み込んで
342set ocidSaveImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidSaveImageRep))
343(ocidSaveImageContext's setShouldAntialias:(true))
344(ocidSaveImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
345(ocidSaveImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentRelativeColorimetric))
346#生成された画像でNSGraphicsContext初期化
347(refMe's NSGraphicsContext's setCurrentContext:(ocidSaveImageContext))
348
349#シャドウをセットして
350ocidSetShadow's |set|()
351#
352set ocidPasteRect to refMe's NSRect's NSMakeRect(0, 0, numW, numH)
353set ocidCopyRect to refMe's NSZeroRect
354#できああっている中間画像をペースト
355(ocidArtBoardRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
356
357#処理終了
358refMe's NSGraphicsContext's restoreGraphicsState()
359####【NSGraphicsContext's】
360
361###########################
362#解像度
363#Retinaで処理した場合
364set numPPI to 144 as integer
365set numWpt to ((numW / numPPI) * 72) as integer
366set numHpt to ((numH / numPPI) * 72) as integer
367set ocidSetSize to refMe's NSSize's NSMakeSize(numWpt, numHpt)
368ocidArtBoardRep's setSize:(ocidSetSize)
369#72ppiモニタで処理した場合
370# set numPPI to 72 as integer
371# set numWpt to ((numW / numPPI) * 72) as integer
372# set numHpt to ((numH / numPPI) * 72) as integer
373# set ocidSetSize to refMe's NSSize's NSMakeSize(numWpt, numHpt)
374# ocidArtBoardRep's setSize:(ocidSetSize)
375
376################
377#保存先 個人用
378set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
379set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
380#ディレクトリ
381set ocidSaveDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/DocumentIcon") isDirectory:(true)
382set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
383ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
384set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
385
386##ファイル名
387set strDateTime to doGetNextDateNo({"yyyyMMddhhmm", 1})
388set strFileName to (strDateTime & "-" & numW & "x" & numH & "@144") as text
389set ocidSaveBasePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:(false)
390set ocidSaveFilePathURL to ocidSaveBasePathURL's URLByAppendingPathExtension:("png")
391
392#保存オプション
393set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
394(ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
395(ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
396(ocidProperty's setObject:(ocidProfileData) forKey:(refMe's NSImageColorSyncProfileData))
397
398#保存データに変換
399set ocidNSInlineData to (ocidSaveImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
400
401#保存
402set listDone to ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference)
403
404
405################
406#Iconsetを作成する
407#設定項目作成するアイコンサイズ
408set listPxSize to {32, 40, 58, 60, 64, 76, 80, 87, 114, 120, 128, 136, 152, 167, 180, 192, 256, 512, 1024} as list
409
410
411#iconsetディレクトリ
412set strSetDirName to ("Icons/DocumentIconSet/" & strDateTime & ".iconset") as text
413set ocidSaveDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:(strSetDirName) isDirectory:(true)
414set ocidSaveDirPath to ocidSaveDirPathURL's |path|()
415set strSaveDirPath to ocidSaveDirPath as text
416#アイコンファイル
417set strSetIconsName to ("Icons/DocumentIconSet/" & strDateTime & ".icns") as text
418set ocidSaveIconsFilePathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:(strSetIconsName) isDirectory:(false)
419set ocidSaveIconsFilePath to ocidSaveIconsFilePathURL's |path|()
420set strSaveIconsFilePath to ocidSaveIconsFilePath as text
421#iconsetのフォルダを作っておく
422set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
423ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
424set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
425
426#NSADATA
427# set ocidOption to (refMe's NSDataReadingMappedIfSafe)
428# set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidSaveFilePathURL) options:(ocidOption) |error| :(reference)
429# set ocidReadData to (item 1 of listResponse)
430
431#NSIMAGE
432# set ocidReadImage to refMe's NSImage's alloc()'s initWithData:(ocidReadData)
433
434#NSBitmapImageRep
435# set ocidReadImgRep to (ocidReadImage's representations)'s firstObject()
436set ocidReadImgRep to ocidSaveImageRep
437set numpixelsWidth to ocidReadImgRep's pixelsWide()
438set numpixelsHeight to ocidReadImgRep's pixelsHigh()
439set ocidSetSize to refMe's NSSize's NSMakeSize(numpixelsWidth, numpixelsHeight)
440ocidReadImgRep's setSize:(ocidSetSize)
441set ocidFromCopyRect to refMe's NSRect's NSMakeRect(0, 0, numpixelsWidth, numpixelsHeight)
442
443####################
444#iconset作成開始
445####################
446
447#設定項目のサイズに従って順番に処理
448repeat with itemPxSize in listPxSize
449  #72ppito144ppiでファイル名を設定
450  set numPxSize to itemPxSize as integer
451  set numHighResPtSize to (numPxSize / 2) as integer
452  set strFileName to ("icon_" & numPxSize & "x" & numPxSize & ".png") as text
453  set strHighResFileName to ("icon_" & numHighResPtSize & "x" & numHighResPtSize & "@2x.png") as text
454  #設定サイズで画像を作成
455  set ocidIconImageRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numPxSize) pixelsHigh:(numPxSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:(true) isPlanar:(false) colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSBitmapFormatAlphaFirst) bytesPerRow:0 bitsPerPixel:32)
456  (ocidIconImageRep's setProperty:(refMe's NSImageColorSyncProfileData) withValue:(ocidProfileData))
457  set ocidDrawPasteRect to refMe's NSRect's NSMakeRect(0, 0, numPxSize, numPxSize)
458  #編集開始
459  refMe's NSGraphicsContext's saveGraphicsState()
460  set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidIconImageRep))
461  (ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
462  (ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentSaturation))
463  (ocidSetImageContext's setCompositingOperation:(refMe's NSCompositingOperationMultiply))
464  (ocidSetImageContext's setShouldAntialias:(true))
465  (refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
466  (ocidReadImgRep's drawInRect:(ocidDrawPasteRect) fromRect:(ocidFromCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
467  #編集終了
468  refMe's NSGraphicsContext's restoreGraphicsState()
469  #72ppi ptサイズ設定
470  set ocidSetSize to refMe's NSSize's NSMakeSize(numPxSize, numPxSize)
471  (ocidIconImageRep's setSize:(ocidSetSize))
472  #72ppiで保存
473  set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
474  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:(false))
475  set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
476  #144ppiでptサイズ設定
477  set ocidSetSize to refMe's NSSize's NSMakeSize(numHighResPtSize, numHighResPtSize)
478  (ocidIconImageRep's setSize:(ocidSetSize))
479  #144ppiで保存
480  set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
481  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strHighResFileName) isDirectory:(false))
482  set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
483  #生成した画像をクリア
484  set ocidIconImageRep to ""
485end repeat
486set ocidFullImageRep to ""
487
488################## 
489#ICNSファイル生成
490set strCommandText to ("/usr/bin/iconutil --convert icns \"" & strSaveDirPath & "\" -o \"" & strSaveIconsFilePath & "\"")
491log "\r" & strCommandText & "\r"
492set ocidComString to refMe's NSString's stringWithString:(strCommandText)
493set ocidTermTask to refMe's NSTask's alloc()'s init()
494ocidTermTask's setLaunchPath:("/bin/zsh")
495set ocidArgumentsArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
496ocidArgumentsArray's addObject:("-c")
497ocidArgumentsArray's addObject:(ocidComString)
498ocidTermTask's setArguments:(ocidArgumentsArray)
499set ocidOutPut to refMe's NSPipe's pipe()
500set ocidError to refMe's NSPipe's pipe()
501ocidTermTask's setStandardOutput:(ocidOutPut)
502ocidTermTask's setStandardError:(ocidError)
503ocidTermTask's setCurrentDirectoryURL:(ocidSaveDirPathURL)
504set listDoneReturn to ocidTermTask's launchAndReturnError:(reference)
505if (item 1 of listDoneReturn) is (false) then
506  log "エラーコード:" & (item 2 of listDoneReturn)'s code() as text
507  log "エラードメイン:" & (item 2 of listDoneReturn)'s domain() as text
508  log "Description:" & (item 2 of listDoneReturn)'s localizedDescription() as text
509  log "FailureReason:" & (item 2 of listDoneReturn)'s localizedFailureReason() as text
510end if
511##################
512#終了待ち
513ocidTermTask's waitUntilExit()
514
515set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
516set boolDone to appSharedWorkspace's selectFile:(ocidSaveIconsFilePath) inFileViewerRootedAtPath:(ocidSaveDirPath)
517
518
519return
520
521if (item 1 of listDone as boolean) is true then
522  ###保存先を開く
523  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
524  set boolDone to appSharedWorkspace's openURL:(ocidSaveDirPathURL)
525  
526end if
527################################
528# 明日の日付 doGetDateNo(argDateFormat,argCalendarNO)
529# argCalendarNO 1 NSCalendarIdentifierGregorian 西暦
530# argCalendarNO 2 NSCalendarIdentifierJapanese 和暦
531################################
532to doGetNextDateNo({argDateFormat, argCalendarNO})
533  ##渡された値をテキストで確定させて
534  set strDateFormat to argDateFormat as text
535  set intCalendarNO to argCalendarNO as integer
536  ###日付情報の取得
537  set ocidDate to current application's NSDate's |date|()
538  set ocidIntervalt to current application's NSDate's dateWithTimeIntervalSinceNow:(86400)
539  ###日付のフォーマットを定義(日本語)
540  set ocidFormatterJP to current application's NSDateFormatter's alloc()'s init()
541  ###和暦 西暦 カレンダー分岐
542  if intCalendarNO = 1 then
543    set ocidCalendarID to (current application's NSCalendarIdentifierGregorian)
544  else if intCalendarNO = 2 then
545    set ocidCalendarID to (current application's NSCalendarIdentifierJapanese)
546  else
547    set ocidCalendarID to (current application's NSCalendarIdentifierISO8601)
548  end if
549  set ocidCalendarJP to current application's NSCalendar's alloc()'s initWithCalendarIdentifier:(ocidCalendarID)
550  set ocidTimezoneJP to current application's NSTimeZone's alloc()'s initWithName:("Asia/Tokyo")
551  set ocidLocaleJP to current application's NSLocale's alloc()'s initWithLocaleIdentifier:("ja_JP_POSIX")
552  ###設定
553  ocidFormatterJP's setTimeZone:(ocidTimezoneJP)
554  ocidFormatterJP's setLocale:(ocidLocaleJP)
555  ocidFormatterJP's setCalendar:(ocidCalendarJP)
556  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterNoStyle)
557  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterShortStyle)
558  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterMediumStyle)
559  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterLongStyle)
560  ocidFormatterJP's setDateStyle:(current application's NSDateFormatterFullStyle)
561  ###渡された値でフォーマット定義
562  ocidFormatterJP's setDateFormat:(strDateFormat)
563  ###フォーマット適応
564  set ocidDateAndTime to ocidFormatterJP's stringFromDate:(ocidIntervalt)
565  ###テキストで戻す
566  set strDateAndTime to ocidDateAndTime as text
567  return strDateAndTime
568end doGetNextDateNo
569return
570
AppleScriptで生成しました

|

アイコン付きフォルダを作る(フォルダにアイコンを付与)の簡素な記述


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.6"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010
011#今の日付
012set objDate to (current date) as date
013set numY to year of objDate as integer
014set numM to month of objDate as integer
015set numD to day of objDate as integer
016#日付をフォルダ名に使う
017set strDirName to (numY & numM & numD) as text
018
019#デスクトップに
020set aliasDesktopDirPath to (path to desktop folder from user domain) as alias
021
022tell application "Finder"
023  #フォルダが無いなら
024  set boolExist to exists of (folder strDirName of folder aliasDesktopDirPath)
025  if boolExist is false then
026    #フォルダを作る
027    make new folder at aliasDesktopDirPath with properties {name:strDirName}
028  end if
029  set aliasDirPath to (folder strDirName of folder aliasDesktopDirPath) as alias
030end tell
031
032#フォルダのパス
033set strDirPath to (POSIX path of aliasDirPath) as text
034set ocidDirPathStr to current application's NSString's stringWithString:(strDirPath)
035set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
036
037#画像のパス
038set strFilePath to ("/System/Library/Desktop Pictures/Hello Metallic Blue.heic") as text
039set ocidFilePathStr to current application's NSString's stringWithString:(strFilePath)
040set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
041set ocidFilePathURL to (current application's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
042
043#画像データを読み込んで
044set ocidImageData to (current application's NSImage's alloc()'s initWithContentsOfURL:(ocidFilePathURL))
045
046#フォルダに貼る
047set appSharedWorkspace to current application's NSWorkspace's sharedWorkspace()
048set ocidOption to (current application's NSExclude10_4ElementsIconCreationOption)
049set boolDone to (appSharedWorkspace's setIcon:(ocidImageData) forFile:(ocidDirPath) options:(ocidOption))
AppleScriptで生成しました

|

より以前の記事一覧

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom