Icon

[NSGraphicsContext]画像からアイコンセットiconsetとアイコンファイルicnsを作成する (元画像の縦横比のまま作成)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# 読み込んだ画像の縦横比のままアイコンファイルを作成します
005# はみ出す部分は透過されます
006#com.cocolog-nifty.quicktimer.icefloe
007----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
008use AppleScript version "2.8"
009use framework "Foundation"
010use framework "UniformTypeIdentifiers"
011use framework "AppKit"
012use scripting additions
013
014property refMe : a reference to current application
015
016set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
017set appFileManager to refMe's NSFileManager's defaultManager()
018#設定項目作成するアイコンサイズ
019set listPxSize to {32, 40, 58, 60, 64, 76, 80, 87, 114, 120, 128, 136, 152, 167, 180, 192, 256, 512, 1024, 2048} as list
020
021###ダイアログ
022set strName to (name of current application) as text
023if strName is "osascript" then
024  tell application "Finder" to activate
025else
026  tell current application to activate
027end if
028set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
029set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
030set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
031set listUTI to {"public.image"} as list
032set strMes to ("ファイルを選んでください") as text
033set strPrompt to ("ファイルを選んでください") as text
034try
035  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
036on error
037  log "エラーしました"
038  return "エラーしました"
039end try
040
041set strFilePath to (POSIX path of aliasFilePath) as text
042set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
043set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
044set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
045set ocidFileName to ocidFilePathURL's lastPathComponent()
046set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
047set ocidSaveDirName to ocidBaseFileName's stringByAppendingPathExtension:("iconset")
048set ocidSaveIcnsFileName to ocidBaseFileName's stringByAppendingPathExtension:("icns")
049#保存先
050set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
051set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
052set ocidIconDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/MakeIcon") isDirectory:(true)
053#iconsetディレクトリ
054set ocidSaveDirPathURL to ocidIconDirPathURL's URLByAppendingPathComponent:(ocidSaveDirName) isDirectory:(true)
055set strSaveDirPath to ocidSaveDirPathURL's |path| as text
056#icnsファイルパス
057set ocidSaveIcnsFilePathURL to ocidIconDirPathURL's URLByAppendingPathComponent:(ocidSaveIcnsFileName) isDirectory:(false)
058set strSaveIcnsFilePath to ocidSaveIcnsFilePathURL's |path| as text
059#iconsetのフォルダを作っておく
060set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
061ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
062set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
063
064#カラー
065set strIccFilePath to ("/System/Library/ColorSync/Profiles/sRGB Profile.icc") as text
066set ocidIccFilePathStr to refMe's NSString's stringWithString:(strIccFilePath)
067set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
068set ocidIccFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidIccFilePath) isDirectory:(false)
069set ocidProfileData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidIccFilePathURL)
070
071#NSADATA
072set ocidOption to (refMe's NSDataReadingMappedIfSafe)
073set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error| :(reference)
074set ocidReadData to (item 1 of listResponse)
075
076#NSIMAGE
077set ocidReadImage to refMe's NSImage's alloc()'s initWithData:(ocidReadData)
078set ocidReadImgRep to (ocidReadImage's representations)'s firstObject()
079set numpixelsWidth to ocidReadImgRep's pixelsWide()
080set numpixelsHeight to ocidReadImgRep's pixelsHigh()
081set ocidSetSize to refMe's NSSize's NSMakeSize(numpixelsWidth, numpixelsHeight)
082ocidReadImgRep's setSize:(ocidSetSize)
083set ocidFromCopyRect to refMe's NSRect's NSMakeRect(0, 0, numpixelsWidth, numpixelsHeight)
084
085#元になる2048pxの画像作成
086set ocidFullImageRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(2048) pixelsHigh:(2048) bitsPerSample:8 samplesPerPixel:4 hasAlpha:(true) isPlanar:(false) colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSBitmapFormatAlphaFirst) bytesPerRow:0 bitsPerPixel:32)
087ocidFullImageRep's setProperty:(refMe's NSImageColorSyncProfileData) withValue:(ocidProfileData)
088#編集開始
089refMe's NSGraphicsContext's saveGraphicsState()
090set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidFullImageRep))
091ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh)
092ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentSaturation)
093ocidSetImageContext's setCompositingOperation:(refMe's NSCompositingOperationMultiply)
094ocidSetImageContext's setShouldAntialias:(true)
095refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext)
096set ocidDrawPasteRect to refMe's NSRect's NSMakeRect(0, 0, 2048, 2048)
097(ocidReadImgRep's drawInRect:(ocidDrawPasteRect) fromRect:(ocidFromCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
098#編集終了
099refMe's NSGraphicsContext's restoreGraphicsState()
100#編集後の元画像の矩形
101set ocidFromCopyRect to refMe's NSRect's NSMakeRect(0, 0, 2048, 2048)
102
103####################
104#iconset作成開始
105####################
106#16サイズだけ個別で作成
107set itemPxSize to 16 as integer
108set ocidIconImageRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(itemPxSize) pixelsHigh:(itemPxSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:(true) isPlanar:(false) colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSBitmapFormatAlphaFirst) bytesPerRow:0 bitsPerPixel:32)
109ocidIconImageRep's setProperty:(refMe's NSImageColorSyncProfileData) withValue:(ocidProfileData)
110#縦型 横型でコピー位置調整
111if numpixelsWidth = numpixelsHeight then
112  set ocidDrawPasteRect to current application's NSRect's NSMakeRect(0, 0, itemPxSize, itemPxSize)
113else if numpixelsWidth > numpixelsHeight then
114  set numRatio to (numpixelsHeight / numpixelsWidth) as number
115  set numSetH to (itemPxSize * numRatio) as integer
116  set numSetY to ((itemPxSize - numSetH) / 2) as integer
117  set ocidDrawPasteRect to current application's NSRect's NSMakeRect(0, numSetY, itemPxSize, numSetH)
118else if numpixelsWidth < numpixelsHeight then
119  set numRatio to (numpixelsWidth / numpixelsHeight) as number
120  set numSetW to (itemPxSize * numRatio) as integer
121  set numSetX to ((itemPxSize - numSetW) / 2) as integer
122  set ocidDrawPasteRect to current application's NSRect's NSMakeRect(numSetX, 0, numSetW, itemPxSize)
123end if
124
125#編集開始
126refMe's NSGraphicsContext's saveGraphicsState()
127set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidIconImageRep))
128ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh)
129ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentSaturation)
130ocidSetImageContext's setCompositingOperation:(refMe's NSCompositingOperationMultiply)
131ocidSetImageContext's setShouldAntialias:(true)
132refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext)
133(ocidFullImageRep's drawInRect:(ocidDrawPasteRect) fromRect:(ocidFromCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
134#編集終了
135refMe's NSGraphicsContext's restoreGraphicsState()
136#解像度設定72ppi
137set ocidSetSize to refMe's NSSize's NSMakeSize(itemPxSize, itemPxSize)
138ocidIconImageRep's setSize:(ocidSetSize)
139#PNG保存オプション
140set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
141(ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
142(ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
143#保存
144set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
145set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("icon_16x16.png") isDirectory:(false)
146set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
147#保存画像を一旦クリア
148set ocidIconImageRep to ""
149
150#設定項目のサイズに従って順番に処理
151repeat with itemPxSize in listPxSize
152  #72ppito144ppiでファイル名を設定
153  set numPxSize to itemPxSize as integer
154  set numHighResPtSize to (numPxSize / 2) as integer
155  set strFileName to ("icon_" & numPxSize & "x" & numPxSize & ".png") as text
156  set strHighResFileName to ("icon_" & numHighResPtSize & "x" & numHighResPtSize & "@2x.png") as text
157  #設定サイズで画像を作成
158  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)
159  (ocidIconImageRep's setProperty:(refMe's NSImageColorSyncProfileData) withValue:(ocidProfileData))
160  if numpixelsWidth = numpixelsHeight then
161    set ocidDrawPasteRect to current application's NSRect's NSMakeRect(0, 0, numPxSize, numPxSize)
162  else if numpixelsWidth > numpixelsHeight then
163    set numRatio to (numpixelsHeight / numpixelsWidth) as number
164    set numSetH to (numPxSize * numRatio) as integer
165    set numSetY to ((numPxSize - numSetH) / 2) as integer
166    set ocidDrawPasteRect to current application's NSRect's NSMakeRect(0, numSetY, numPxSize, numSetH)
167  else if numpixelsWidth < numpixelsHeight then
168    set numRatio to (numpixelsWidth / numpixelsHeight) as number
169    set numSetW to (numPxSize * numRatio) as integer
170    set numSetX to ((numPxSize - numSetW) / 2) as integer
171    set ocidDrawPasteRect to current application's NSRect's NSMakeRect(numSetX, 0, numSetW, numPxSize)
172  end if
173  #編集開始
174  refMe's NSGraphicsContext's saveGraphicsState()
175  set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidIconImageRep))
176  (ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
177  (ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentSaturation))
178  (ocidSetImageContext's setCompositingOperation:(refMe's NSCompositingOperationMultiply))
179  (ocidSetImageContext's setShouldAntialias:(true))
180  (refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
181  (ocidFullImageRep's drawInRect:(ocidDrawPasteRect) fromRect:(ocidFromCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
182  #編集終了
183  refMe's NSGraphicsContext's restoreGraphicsState()
184  #72ppi ptサイズ設定
185  set ocidSetSize to refMe's NSSize's NSMakeSize(numPxSize, numPxSize)
186  (ocidIconImageRep's setSize:(ocidSetSize))
187  #72ppiで保存
188  set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
189  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:(false))
190  set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
191  #144ppiでptサイズ設定
192  set ocidSetSize to refMe's NSSize's NSMakeSize(numHighResPtSize, numHighResPtSize)
193  (ocidIconImageRep's setSize:(ocidSetSize))
194  #144ppiで保存
195  set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
196  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strHighResFileName) isDirectory:(false))
197  set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
198  #生成した画像をクリア
199  set ocidIconImageRep to ""
200end repeat
201set ocidFullImageRep to ""
202
203################## 
204#ICNSファイル生成
205set strCommandText to ("/usr/bin/iconutil --convert icns \"" & strSaveDirPath & "\" -o \"" & strSaveIcnsFilePath & "\"")
206log "\r" & strCommandText & "\r"
207set ocidComString to refMe's NSString's stringWithString:(strCommandText)
208set ocidTermTask to refMe's NSTask's alloc()'s init()
209ocidTermTask's setLaunchPath:("/bin/zsh")
210set ocidArgumentsArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
211ocidArgumentsArray's addObject:("-c")
212ocidArgumentsArray's addObject:(ocidComString)
213ocidTermTask's setArguments:(ocidArgumentsArray)
214set ocidOutPut to refMe's NSPipe's pipe()
215set ocidError to refMe's NSPipe's pipe()
216ocidTermTask's setStandardOutput:(ocidOutPut)
217ocidTermTask's setStandardError:(ocidError)
218ocidTermTask's setCurrentDirectoryURL:(ocidIconDirPathURL)
219set listDoneReturn to ocidTermTask's launchAndReturnError:(reference)
220if (item 1 of listDoneReturn) is (false) then
221  log "エラーコード:" & (item 2 of listDoneReturn)'s code() as text
222  log "エラードメイン:" & (item 2 of listDoneReturn)'s domain() as text
223  log "Description:" & (item 2 of listDoneReturn)'s localizedDescription() as text
224  log "FailureReason:" & (item 2 of listDoneReturn)'s localizedFailureReason() as text
225end if
226##################
227#終了待ち
228ocidTermTask's waitUntilExit()
229
230set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
231set boolDone to appSharedWorkspace's selectFile:(ocidSaveIcnsFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidIconDirPathURL's |path|())
232
233return "終了"
AppleScriptで生成しました

|

[NSGraphicsContext]画像からアイコンセットiconsetとアイコンファイルicnsを作成する (短辺でCROP)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# 縦 横 関係なく 中央部を正方形にCROPしてアイコンを作成
004#
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "UniformTypeIdentifiers"
010use framework "AppKit"
011use scripting additions
012
013property refMe : a reference to current application
014
015set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
016set appFileManager to refMe's NSFileManager's defaultManager()
017#設定項目作成するアイコンサイズ
018set listPxSize to {32, 40, 58, 60, 64, 76, 80, 87, 114, 120, 128, 136, 152, 167, 180, 192, 256, 512, 1024, 2048} as list
019
020###ダイアログ
021set strName to (name of current application) as text
022if strName is "osascript" then
023  tell application "Finder" to activate
024else
025  tell current application to activate
026end if
027set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
028set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
029set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
030set listUTI to {"public.image"} as list
031set strMes to ("ファイルを選んでください") as text
032set strPrompt to ("ファイルを選んでください") as text
033try
034  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
035on error
036  log "エラーしました"
037  return "エラーしました"
038end try
039
040set strFilePath to (POSIX path of aliasFilePath) as text
041set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
042set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
043set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
044set ocidFileName to ocidFilePathURL's lastPathComponent()
045set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
046set ocidSaveDirName to ocidBaseFileName's stringByAppendingPathExtension:("iconset")
047set ocidSaveIcnsFileName to ocidBaseFileName's stringByAppendingPathExtension:("icns")
048#保存先
049set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
050set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
051set ocidIconDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/MakeIcon") isDirectory:(true)
052#iconsetディレクトリ
053set ocidSaveDirPathURL to ocidIconDirPathURL's URLByAppendingPathComponent:(ocidSaveDirName) isDirectory:(true)
054set strSaveDirPath to ocidSaveDirPathURL's |path| as text
055#icnsファイルパス
056set ocidSaveIcnsFilePathURL to ocidIconDirPathURL's URLByAppendingPathComponent:(ocidSaveIcnsFileName) isDirectory:(false)
057set strSaveIcnsFilePath to ocidSaveIcnsFilePathURL's |path| as text
058#iconsetのフォルダを作っておく
059set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
060ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
061set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
062
063#カラー
064set strIccFilePath to ("/System/Library/ColorSync/Profiles/sRGB Profile.icc") as text
065set ocidIccFilePathStr to refMe's NSString's stringWithString:(strIccFilePath)
066set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
067set ocidIccFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidIccFilePath) isDirectory:(false)
068set ocidProfileData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidIccFilePathURL)
069
070#NSADATA
071set ocidOption to (refMe's NSDataReadingMappedIfSafe)
072set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error| :(reference)
073set ocidReadData to (item 1 of listResponse)
074
075#NSIMAGE
076set ocidReadImage to refMe's NSImage's alloc()'s initWithData:(ocidReadData)
077set ocidReadImgRep to (ocidReadImage's representations)'s firstObject()
078set numpixelsWidth to ocidReadImgRep's pixelsWide()
079set numpixelsHeight to ocidReadImgRep's pixelsHigh()
080set ocidSetSize to refMe's NSSize's NSMakeSize(numpixelsWidth, numpixelsHeight)
081ocidReadImgRep's setSize:(ocidSetSize)
082
083#縦型 横型でコピー位置調整
084if numpixelsWidth = numpixelsHeight then
085  set ocidFromCopyRect to refMe's NSRect's NSMakeRect(0, 0, numpixelsWidth, numpixelsHeight)
086else if numpixelsWidth > numpixelsHeight then
087  set numDiff to ((numpixelsWidth - numpixelsHeight) / 2) as integer
088  set ocidFromCopyRect to refMe's NSRect's NSMakeRect(numDiff, 0, numpixelsHeight, numpixelsHeight)
089else if numpixelsWidth < numpixelsHeight then
090  set numDiff to ((numpixelsHeight - numpixelsWidth) / 2) as integer
091  set ocidFromCopyRect to refMe's NSRect's NSMakeRect(0, numDiff, numpixelsWidth, numpixelsWidth)
092end if
093
094#元になる2048pxの画像作成
095set ocidFullImageRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(2048) pixelsHigh:(2048) bitsPerSample:8 samplesPerPixel:4 hasAlpha:(true) isPlanar:(false) colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSBitmapFormatAlphaFirst) bytesPerRow:0 bitsPerPixel:32)
096ocidFullImageRep's setProperty:(refMe's NSImageColorSyncProfileData) withValue:(ocidProfileData)
097#編集開始
098refMe's NSGraphicsContext's saveGraphicsState()
099set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidFullImageRep))
100ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh)
101ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentSaturation)
102ocidSetImageContext's setCompositingOperation:(refMe's NSCompositingOperationMultiply)
103ocidSetImageContext's setShouldAntialias:(true)
104refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext)
105set ocidDrawPasteRect to refMe's NSRect's NSMakeRect(0, 0, 2048, 2048)
106(ocidReadImgRep's drawInRect:(ocidDrawPasteRect) fromRect:(ocidFromCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
107#編集終了
108refMe's NSGraphicsContext's restoreGraphicsState()
109#編集後の元画像の矩形
110set ocidFromCopyRect to refMe's NSRect's NSMakeRect(0, 0, 2048, 2048)
111
112####################
113#iconset作成開始
114####################
115#16サイズだけ個別で作成
116set itemPxSize to 16 as integer
117set ocidIconImageRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(itemPxSize) pixelsHigh:(itemPxSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:(true) isPlanar:(false) colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSBitmapFormatAlphaFirst) bytesPerRow:0 bitsPerPixel:32)
118ocidIconImageRep's setProperty:(refMe's NSImageColorSyncProfileData) withValue:(ocidProfileData)
119set ocidDrawPasteRect to refMe's NSRect's NSMakeRect(0, 0, itemPxSize, itemPxSize)
120#編集開始
121refMe's NSGraphicsContext's saveGraphicsState()
122set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidIconImageRep))
123ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh)
124ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentSaturation)
125ocidSetImageContext's setCompositingOperation:(refMe's NSCompositingOperationMultiply)
126ocidSetImageContext's setShouldAntialias:(true)
127refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext)
128(ocidFullImageRep's drawInRect:(ocidDrawPasteRect) fromRect:(ocidFromCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
129#編集終了
130refMe's NSGraphicsContext's restoreGraphicsState()
131#解像度設定72ppi
132set ocidSetSize to refMe's NSSize's NSMakeSize(itemPxSize, itemPxSize)
133ocidIconImageRep's setSize:(ocidSetSize)
134#PNG保存オプション
135set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
136(ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
137(ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
138#保存
139set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
140set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("icon_16x16.png") isDirectory:(false)
141set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
142#保存画像を一旦クリア
143set ocidIconImageRep to ""
144
145#設定項目のサイズに従って順番に処理
146repeat with itemPxSize in listPxSize
147  #72ppito144ppiでファイル名を設定
148  set numPxSize to itemPxSize as integer
149  set numHighResPtSize to (numPxSize / 2) as integer
150  set strFileName to ("icon_" & numPxSize & "x" & numPxSize & ".png") as text
151  set strHighResFileName to ("icon_" & numHighResPtSize & "x" & numHighResPtSize & "@2x.png") as text
152  #設定サイズで画像を作成
153  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)
154  (ocidIconImageRep's setProperty:(refMe's NSImageColorSyncProfileData) withValue:(ocidProfileData))
155  set ocidDrawPasteRect to refMe's NSRect's NSMakeRect(0, 0, numPxSize, numPxSize)
156  #編集開始
157  refMe's NSGraphicsContext's saveGraphicsState()
158  set ocidSetImageContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidIconImageRep))
159  (ocidSetImageContext's setImageInterpolation:(refMe's NSImageInterpolationHigh))
160  (ocidSetImageContext's setColorRenderingIntent:(refMe's NSColorRenderingIntentSaturation))
161  (ocidSetImageContext's setCompositingOperation:(refMe's NSCompositingOperationMultiply))
162  (ocidSetImageContext's setShouldAntialias:(true))
163  (refMe's NSGraphicsContext's setCurrentContext:(ocidSetImageContext))
164  (ocidFullImageRep's drawInRect:(ocidDrawPasteRect) fromRect:(ocidFromCopyRect) operation:(refMe's NSCompositingOperationSourceOver) fraction:(1.0) respectFlipped:(false) hints:(missing value))
165  #編集終了
166  refMe's NSGraphicsContext's restoreGraphicsState()
167  #72ppi ptサイズ設定
168  set ocidSetSize to refMe's NSSize's NSMakeSize(numPxSize, numPxSize)
169  (ocidIconImageRep's setSize:(ocidSetSize))
170  #72ppiで保存
171  set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
172  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:(false))
173  set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
174  #144ppiでptサイズ設定
175  set ocidSetSize to refMe's NSSize's NSMakeSize(numHighResPtSize, numHighResPtSize)
176  (ocidIconImageRep's setSize:(ocidSetSize))
177  #144ppiで保存
178  set ocidNSInlineData to (ocidIconImageRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
179  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strHighResFileName) isDirectory:(false))
180  set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
181  #生成した画像をクリア
182  set ocidIconImageRep to ""
183end repeat
184set ocidFullImageRep to ""
185
186################## 
187#ICNSファイル生成
188set strCommandText to ("/usr/bin/iconutil --convert icns \"" & strSaveDirPath & "\" -o \"" & strSaveIcnsFilePath & "\"")
189log "\r" & strCommandText & "\r"
190set ocidComString to refMe's NSString's stringWithString:(strCommandText)
191set ocidTermTask to refMe's NSTask's alloc()'s init()
192ocidTermTask's setLaunchPath:("/bin/zsh")
193set ocidArgumentsArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
194ocidArgumentsArray's addObject:("-c")
195ocidArgumentsArray's addObject:(ocidComString)
196ocidTermTask's setArguments:(ocidArgumentsArray)
197set ocidOutPut to refMe's NSPipe's pipe()
198set ocidError to refMe's NSPipe's pipe()
199ocidTermTask's setStandardOutput:(ocidOutPut)
200ocidTermTask's setStandardError:(ocidError)
201ocidTermTask's setCurrentDirectoryURL:(ocidIconDirPathURL)
202set listDoneReturn to ocidTermTask's launchAndReturnError:(reference)
203if (item 1 of listDoneReturn) is (false) then
204  log "エラーコード:" & (item 2 of listDoneReturn)'s code() as text
205  log "エラードメイン:" & (item 2 of listDoneReturn)'s domain() as text
206  log "Description:" & (item 2 of listDoneReturn)'s localizedDescription() as text
207  log "FailureReason:" & (item 2 of listDoneReturn)'s localizedFailureReason() as text
208end if
209##################
210#終了待ち
211ocidTermTask's waitUntilExit()
212
213set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
214set boolDone to appSharedWorkspace's selectFile:(ocidSaveIcnsFilePathURL's |path|()) inFileViewerRootedAtPath:(ocidIconDirPathURL's |path|())
215
216return "終了"
AppleScriptで生成しました

|

クリップボードのアイコンイメージをicnsファイルに(修正)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005#
006#
007# com.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
014
015property refMe : a reference to current application
016
017################################
018##### パス関連
019################################
020###ファイル名用に時間を取得する
021set strDateno to doGetDateNo("yyyyMMddhhmmss") as text
022###保存先
023set strFilePath to "~/Desktop/Icons-" & strDateno & ".icns" as text
024set ocidFilePathStr to refMe's NSString's stringWithString:strFilePath
025set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
026set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false
027
028################################
029######ペーストボードを取得
030################################
031set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
032####タイプを取得
033set ocidPastBoardTypeArray to ocidPasteboard's types()
034log ocidPastBoardTypeArray as list
035#####イメージがあれば
036set boolContain to ocidPastBoardTypeArray's containsObject:"com.apple.icns"
037if boolContain is true then
038  set ocidIconData to ocidPasteboard's dataForType:("com.apple.icns")
039else
040  return "イメージ以外なので中止"
041end if
042
043################################
044##### 保存
045################################
046set listDone to (ocidIconData's writeToURL:(ocidFilePathURL) options:(current application's NSDataWritingAtomic) |error| :(reference))
047################################
048##### ファイル名用の時間
049################################
050to doGetDateNo(strDateFormat)
051  ####日付情報の取得
052  set ocidDate to current application's NSDate's |date|()
053  ###日付のフォーマットを定義
054  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
055  ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
056  ocidNSDateFormatter's setDateFormat:strDateFormat
057  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
058  set strDateAndTime to ocidDateAndTime as text
059  return strDateAndTime
060end doGetDateNo
AppleScriptで生成しました

|

[NSISIconImageRep]フォルダのアイコンをicnsファイルにする


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005# com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012
013###中間ファイルのアイコンセットを残すか?
014# true 残す ピクチャーフォルダ内に残る
015# false 処理終了時にゴミ箱に入れる
016property boolSaveIconSet : true as boolean
017
018#ダイアログを前面に出す
019set strName to (name of current application) as text
020if strName is "osascript" then
021  tell application "Finder" to activate
022else
023  tell current application to activate
024end if
025set appFileManager to current application's NSFileManager's defaultManager()
026set ocidUserDesktopPathURLArray to (appFileManager's URLsForDirectory:(current application's NSDesktopDirectory) inDomains:(current application's NSUserDomainMask))
027set ocidUserDesktopPathURL to ocidUserDesktopPathURLArray's firstObject()
028set aliasDefaultLocation to (ocidUserDesktopPathURL's absoluteURL()) as alias
029set listUTI to {"public.item"} as list
030set strPromptText to "ファイルを選んでください" as text
031set strMesText to "ファイルを選んでください" as text
032##
033set aliasFilePath to (choose folder strMesText with prompt strPromptText default location (aliasDefaultLocation) with invisibles and showing package contents without multiple selections allowed) as alias
034#
035set strFilePath to (POSIX path of aliasFilePath) as text
036set ocidFilePathStr to current application's NSString's stringWithString:(strFilePath)
037set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
038set ocidFilePathURL to current application's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false)
039#ファイル名
040set ocidFileName to ocidFilePathURL's lastPathComponent()
041set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
042#保存先アイコンファイル
043#デスクトップに保存する場合
044set ocidURLsArray to (appFileManager's URLsForDirectory:(current application's NSDesktopDirectory) inDomains:(current application's NSUserDomainMask))
045set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
046set ocidBaseDesktopFileURL to ocidDesktopDirPathURL's URLByAppendingPathComponent:(ocidBaseFileName) isDirectory:(false)
047set ocidSaveIconFilePathURL to ocidBaseDesktopFileURL's URLByAppendingPathExtension:("icns")
048(* 同じ階層に残す場合
049set ocidIconBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
050set ocidSaveIconFilePathURL to ocidIconBaseFilePathURL's URLByAppendingPathExtension:("icns")
051*)
052set strSaveIconFilePath to ocidSaveIconFilePathURL's |path| as text
053#保存先 アイコンセット
054set ocidURLsArray to (appFileManager's URLsForDirectory:(current application's NSPicturesDirectory) inDomains:(current application's NSUserDomainMask))
055set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
056set ocidSaveDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GetIcon/") isDirectory:(true))
057#ファイル名からアイコンセット名
058
059set ocidBaseSubDirURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidBaseFileName) isDirectory:(false)
060set ocidIconSetDirPathURL to ocidBaseSubDirURL's URLByAppendingPathExtension:("iconset")
061set strIconSetDirPath to ocidIconSetDirPathURL's |path| as text
062
063#iconsetのフォルダ作成
064set ocidAttrDict to current application's NSMutableDictionary's alloc()'s initWithCapacity:0
065ocidAttrDict's setValue:(448) forKey:(current application's NSFilePosixPermissions)
066set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidIconSetDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
067#アイコンデータの収集
068#無駄だけどNSURLCustomIconKeyで取得して
069set listResponse to (ocidFilePathURL's getResourceValue:(reference) forKey:(current application's NSURLCustomIconKey) |error| :(reference))
070set ocidIconData to (item 2 of listResponse)
071#取得出来なかったら
072if ocidIconData = (missing value) then
073  #NSWorkspaceでアイコンデータを取得
074  set appSharedWorkspace to current application's NSWorkspace's sharedWorkspace()
075  set ocidIconData to appSharedWorkspace's iconForFile:(ocidFilePath)
076end if
077#取得したNSIMAGEを展開
078set ocidRepArray to ocidIconData's representations()
079set setReFileName to missing value
080#PNG保存オプション
081set ocidProperty to (current application's NSMutableDictionary's alloc()'s initWithCapacity:0)
082(ocidProperty's setObject:(current application's NSNumber's numberWithBool:false) forKey:(current application's NSImageInterlaced))
083(ocidProperty's setObject:(current application's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(current application's NSImageGamma))
084
085#順番に処理
086repeat with itemImageRep in ocidRepArray
087  #ピクセルサイズ
088  set numPixelsWide to itemImageRep's pixelsWide() as integer
089  set numPixelsHigh to itemImageRep's pixelsHigh() as integer
090  #ポイントサイズ
091  set numPtWide to (itemImageRep's |size|())'s width() as integer
092  set numPtHight to (itemImageRep's |size|())'s height() as integer
093  #解像度で分岐
094  if numPixelsWide = numPtWide then
095    #72ppiの場合
096    set strSaveFileName to ("icon_" & numPixelsWide & "x" & numPixelsHigh & ".png") as text
097    set ocidCopyRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide), height:(numPixelsHigh)}}
098    set ocidPasteRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide), height:(numPixelsHigh)}}
099    set ocidSetSize to current application's NSSize's NSMakeSize(numPixelsWide, numPixelsWide)
100  else
101    #144ppiの場合
102    set strSaveFileName to ("icon_" & numPixelsWide & "x" & numPixelsHigh & "@2x.png") as text
103    set ocidCopyRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide), height:(numPixelsHigh)}}
104    set ocidPasteRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide * 2), height:(numPixelsHigh * 2)}}
105    set ocidSetSize to current application's NSSize's NSMakeSize(numPtWide, numPtHight)
106  end if
107  #NSISIconImageRepを処理するために画像をDRAWする
108  #同サイズの新規イメージを作って
109  set ocidAardboardRep to (current application's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numPixelsWide) pixelsHigh:(numPixelsHigh) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(current application's NSCalibratedRGBColorSpace) bitmapFormat:(current application's NSBitmapFormatAlphaFirst) bytesPerRow:0 bitsPerPixel:32)
110  ###編集開始
111  set ocidGraphicsContext to current application's NSGraphicsContext
112  ocidGraphicsContext's saveGraphicsState()
113  (ocidGraphicsContext's setCurrentContext:(ocidGraphicsContext's graphicsContextWithBitmapImageRep:(ocidAardboardRep)))
114  #アイコンイメージをペースト
115  (itemImageRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(current application's NSCompositingOperationSourceOver) fraction:1.0 respectFlipped:false hints:(missing value))
116  ocidGraphicsContext's restoreGraphicsState()
117  (ocidAardboardRep's setSize:(ocidSetSize))
118  ###編集終了
119  #PNGイメージデータに変換
120  set ocidNSInlineData to (ocidAardboardRep's representationUsingType:(current application's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
121  #保存ファイルパス
122  set ocidSaveImageFilePathURL to (ocidIconSetDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
123  #同じファイル名なら処理しない
124  if setReFileName is strSaveFileName then
125    set setReFileName to strSaveFileName
126  else
127    #ファイル名が違うなら保存
128    set listDone to (ocidNSInlineData's writeToURL:(ocidSaveImageFilePathURL) options:(current application's NSDataWritingAtomic) |error| :(reference))
129  end if
130end repeat
131
132set strCommandText to ("/usr/bin/iconutil --convert icns \"" & strIconSetDirPath & "\" -o \"" & strSaveIconFilePath & "\"")
133log "\r" & strCommandText & "\r"
134set strExec to "/bin/zsh -c '" & strCommandText & "'"
135try
136  do shell script strExec
137end try
138
139if boolSaveIconSet is false then
140  set listDone to (appFileManager's trashItemAtURL:(ocidIconSetDirPathURL) resultingItemURL:(ocidIconSetDirPathURL) |error| :(reference))
141  if (item 2 of listDone) ≠ (missing value) then
142    set strErrorNO to (item 2 of listDone)'s code() as text
143    set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
144    current application's NSLog("■:" & strErrorNO & strErrorMes)
145    return "エラーしました" & strErrorNO & strErrorMes
146  end if
147end if
148return
AppleScriptで生成しました

|

[NSISIconImageRep]ファイルのアイコンをicnsファイルにする


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005# com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012
013###中間ファイルのアイコンセットを残すか?
014# true 残す ピクチャーフォルダ内に残る
015# false 処理終了時にゴミ箱に入れる
016property boolSaveIconSet : true as boolean
017
018#ダイアログを前面に出す
019set strName to (name of current application) as text
020if strName is "osascript" then
021  tell application "Finder" to activate
022else
023  tell current application to activate
024end if
025set appFileManager to current application's NSFileManager's defaultManager()
026set ocidUserDesktopPathURLArray to (appFileManager's URLsForDirectory:(current application's NSDesktopDirectory) inDomains:(current application's NSUserDomainMask))
027set ocidUserDesktopPathURL to ocidUserDesktopPathURLArray's firstObject()
028set aliasDefaultLocation to (ocidUserDesktopPathURL's absoluteURL()) as alias
029set listUTI to {"public.item"} as list
030set strPromptText to "ファイルを選んでください" as text
031set strMesText to "ファイルを選んでください" as text
032##
033set aliasFilePath to (choose file strMesText with prompt strPromptText default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
034#
035set strFilePath to (POSIX path of aliasFilePath) as text
036set ocidFilePathStr to current application's NSString's stringWithString:(strFilePath)
037set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
038set ocidFilePathURL to current application's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false)
039set ocidFileName to ocidFilePathURL's lastPathComponent()
040set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
041#保存先アイコンファイル
042#デスクトップに保存する場合
043set ocidURLsArray to (appFileManager's URLsForDirectory:(current application's NSDesktopDirectory) inDomains:(current application's NSUserDomainMask))
044set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
045set ocidBaseDesktopFileURL to ocidDesktopDirPathURL's URLByAppendingPathComponent:(ocidBaseFileName) isDirectory:(false)
046set ocidSaveIconFilePathURL to ocidBaseDesktopFileURL's URLByAppendingPathExtension:("icns")
047
048(* 同じ階層に残す場合
049set ocidIconBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
050set ocidSaveIconFilePathURL to ocidIconBaseFilePathURL's URLByAppendingPathExtension:("icns")
051*)
052set strSaveIconFilePath to ocidSaveIconFilePathURL's |path| as text
053#保存先 アイコンセット
054set ocidURLsArray to (appFileManager's URLsForDirectory:(current application's NSPicturesDirectory) inDomains:(current application's NSUserDomainMask))
055set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
056set ocidSaveDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GetIcon/") isDirectory:(true))
057#ファイル名からアイコンセット名
058set ocidBaseSubDirURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidBaseFileName) isDirectory:(false)
059set ocidIconSetDirPathURL to ocidBaseSubDirURL's URLByAppendingPathExtension:("iconset")
060set strIconSetDirPath to ocidIconSetDirPathURL's |path| as text
061
062#iconsetのフォルダ作成
063set ocidAttrDict to current application's NSMutableDictionary's alloc()'s initWithCapacity:0
064ocidAttrDict's setValue:(448) forKey:(current application's NSFilePosixPermissions)
065set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidIconSetDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
066#アイコンデータの収集
067#無駄だけどNSURLCustomIconKeyで取得して
068set listResponse to (ocidFilePathURL's getResourceValue:(reference) forKey:(current application's NSURLCustomIconKey) |error| :(reference))
069set ocidIconData to (item 2 of listResponse)
070#取得出来なかったら
071if ocidIconData = (missing value) then
072  #NSWorkspaceでアイコンデータを取得
073  set appSharedWorkspace to current application's NSWorkspace's sharedWorkspace()
074  set ocidIconData to appSharedWorkspace's iconForFile:(ocidFilePath)
075end if
076#取得したNSIMAGEを展開
077set ocidRepArray to ocidIconData's representations()
078set setReFileName to missing value
079#PNG保存オプション
080set ocidProperty to (current application's NSMutableDictionary's alloc()'s initWithCapacity:0)
081(ocidProperty's setObject:(current application's NSNumber's numberWithBool:false) forKey:(current application's NSImageInterlaced))
082(ocidProperty's setObject:(current application's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(current application's NSImageGamma))
083
084#順番に処理
085repeat with itemImageRep in ocidRepArray
086  #ピクセルサイズ
087  set numPixelsWide to itemImageRep's pixelsWide() as integer
088  set numPixelsHigh to itemImageRep's pixelsHigh() as integer
089  #ポイントサイズ
090  set numPtWide to (itemImageRep's |size|())'s width() as integer
091  set numPtHight to (itemImageRep's |size|())'s height() as integer
092  #解像度で分岐
093  if numPixelsWide = numPtWide then
094    #72ppiの場合
095    set strSaveFileName to ("icon_" & numPixelsWide & "x" & numPixelsHigh & ".png") as text
096    set ocidCopyRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide), height:(numPixelsHigh)}}
097    set ocidPasteRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide), height:(numPixelsHigh)}}
098    set ocidSetSize to current application's NSSize's NSMakeSize(numPixelsWide, numPixelsWide)
099  else
100    #144ppiの場合
101    set strSaveFileName to ("icon_" & numPixelsWide & "x" & numPixelsHigh & "@2x.png") as text
102    set ocidCopyRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide), height:(numPixelsHigh)}}
103    set ocidPasteRect to {origin:{x:(0), y:(0)}, |size|:{width:(numPixelsWide * 2), height:(numPixelsHigh * 2)}}
104    set ocidSetSize to current application's NSSize's NSMakeSize(numPtWide, numPtHight)
105  end if
106  #NSISIconImageRepを処理するために画像をDRAWする
107  #同サイズの新規イメージを作って
108  set ocidAardboardRep to (current application's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numPixelsWide) pixelsHigh:(numPixelsHigh) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(current application's NSCalibratedRGBColorSpace) bitmapFormat:(current application's NSBitmapFormatAlphaFirst) bytesPerRow:0 bitsPerPixel:32)
109  ###編集開始
110  set ocidGraphicsContext to current application's NSGraphicsContext
111  ocidGraphicsContext's saveGraphicsState()
112  (ocidGraphicsContext's setCurrentContext:(ocidGraphicsContext's graphicsContextWithBitmapImageRep:(ocidAardboardRep)))
113  #アイコンイメージをペースト
114  (itemImageRep's drawInRect:(ocidPasteRect) fromRect:(ocidCopyRect) operation:(current application's NSCompositingOperationSourceOver) fraction:1.0 respectFlipped:false hints:(missing value))
115  ocidGraphicsContext's restoreGraphicsState()
116  (ocidAardboardRep's setSize:(ocidSetSize))
117  ###編集終了
118  #PNGイメージデータに変換
119  set ocidNSInlineData to (ocidAardboardRep's representationUsingType:(current application's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
120  #保存ファイルパス
121  set ocidSaveImageFilePathURL to (ocidIconSetDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
122  #同じファイル名なら処理しない
123  if setReFileName is strSaveFileName then
124    set setReFileName to strSaveFileName
125  else
126    #ファイル名が違うなら保存
127    set listDone to (ocidNSInlineData's writeToURL:(ocidSaveImageFilePathURL) options:(current application's NSDataWritingAtomic) |error| :(reference))
128  end if
129end repeat
130
131set strCommandText to ("/usr/bin/iconutil --convert icns \"" & strIconSetDirPath & "\" -o \"" & strSaveIconFilePath & "\"")
132log "\r" & strCommandText & "\r"
133set strExec to "/bin/zsh -c '" & strCommandText & "'"
134try
135  do shell script strExec
136end try
137
138if boolSaveIconSet is false then
139  set listDone to (appFileManager's trashItemAtURL:(ocidIconSetDirPathURL) resultingItemURL:(ocidIconSetDirPathURL) |error| :(reference))
140  if (item 2 of listDone) ≠ (missing value) then
141    set strErrorNO to (item 2 of listDone)'s code() as text
142    set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
143    current application's NSLog("■:" & strErrorNO & strErrorMes)
144    return "エラーしました" & strErrorNO & strErrorMes
145  end if
146end if
147return
AppleScriptで生成しました

|

アプリケーションの内包アイコンファイルの収集



ダウンロード - copyappicon.zip




AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "UniformTypeIdentifiers"
010use framework "AppKit"
011use scripting additions
012
013property refMe : a reference to current application
014
015set appFileManager to refMe's NSFileManager's defaultManager()
016
017#############################
018#ダイアログ
019#アプリケーション瀬🆃ん拓
020set strName to (name of current application) as text
021if strName is "osascript" then
022  tell application "Finder" to activate
023else
024  tell current application to activate
025end if
026set appFileManager to refMe's NSFileManager's defaultManager()
027set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSApplicationDirectory) inDomains:(refMe's NSLocalDomainMask))
028set ocidApplicationDirPathURL to ocidURLsArray's firstObject()
029set aliasDefaultLocation to (ocidApplicationDirPathURL's absoluteURL()) as alias
030set listUTI to {"com.apple.application-bundle"}
031set strMes to ("ファイルを選んでください") as text
032set strPrompt to ("ファイルを選んでください") as text
033try
034  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with invisibles without multiple selections allowed and showing package contents) as alias
035on error
036  log "エラーしました"
037  return "エラーしました"
038end try
039#アプリケーションのパス
040set strFilePath to (POSIX path of aliasFilePath) as text
041set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
042set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
043set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(true)
044#バンドルID
045set ocidBunndle to refMe's NSBundle's bundleWithURL:(ocidFilePathURL)
046set ocidBunndleID to ocidBunndle's bundleIdentifier()
047set strBunndleID to (ocidBunndleID) as text
048#missing value対策
049if strBunndleID is "" then
050  tell application "Finder"
051    set objInfo to info for aliasFilePath
052    set strBunndleID to bundle identifier of objInfo as text
053  end tell
054end if
055#保存先
056set appFileManager to refMe's NSFileManager's defaultManager()
057set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
058set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
059set strSetPath to ("Icons/AppIcon/" & strBunndleID) as text
060set ocidSaveDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:(strSetPath) isDirectory:(true)
061#保存先確保
062set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
063ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
064set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
065#URL収集
066#プロパティ
067set ocidPropertiesArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
068ocidPropertiesArray's addObject:(refMe's NSURLIsDirectoryKey)
069ocidPropertiesArray's addObject:(refMe's NSURLContentTypeKey)
070ocidPropertiesArray's addObject:(refMe's NSURLPathKey)
071#オプション
072set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
073#収集
074set ocidEmuDict to appFileManager's enumeratorAtURL:(ocidFilePathURL) includingPropertiesForKeys:(ocidPropertiesArray) options:(ocidOption) errorHandler:(reference)
075#収集済みを入れるArray
076set ocidImageFilePathURLAllArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
077#対象のUTI
078set strUTI to ("public.image") as text
079##allObjectsでループする方法
080set ocidEmuFileURLArray to ocidEmuDict's allObjects()
081
082repeat with itemURL in ocidEmuFileURLArray
083  #判定
084  set listResponse to (itemURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error| :(reference))
085  set ocidUTType to (item 2 of listResponse)
086  #URLのUTTyepの親要素を取得して
087  set ocidParentUTIArray to (ocidUTType's supertypes())'s allObjects()
088  #親要素(この属性なら処理する)のUTType
089  set ocidChkUTType to (refMe's UTType's typeWithIdentifier:(strUTI))
090  #含まれているか?チェックする
091  set boolContain to (ocidParentUTIArray's containsObject:(ocidChkUTType))
092  if boolContain is true then
093    log "含まれているので処理対象=画像ファイル"
094    #出力用のリストに追加していく
095    (ocidImageFilePathURLAllArray's addObject:(itemURL))
096  else if boolContain is false then
097    log "含まれてない=画像ではない"
098  end if
099  
100end repeat
101
102##収集したURLをコピー
103repeat with itemURL in ocidImageFilePathURLAllArray
104  #保存先URLにして
105  set ocidFileName to itemURL's lastPathComponent()
106  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:(false))
107  #コピー
108  set listDone to (appFileManager's copyItemAtURL:(itemURL) toURL:(ocidSaveFilePathURL) |error| :(reference))
109end repeat
110
111#Assets.car
112set ocidAssetsFilePathURL to (ocidFilePathURL's URLByAppendingPathComponent:("Contents/Resources/Assets.car") isDirectory:(false))
113set ocidFilePath to ocidAssetsFilePathURL's |path|()
114set boolFileExists to appFileManager's fileExistsAtPath:(ocidFilePath) isDirectory:(false)
115#アセットがある場合
116if boolFileExists = true then
117  set strFilePath to ocidAssetsFilePathURL's |path| as text
118  
119  #Binパス
120  set aliasPathToMe to (path to me) as alias
121  set strPathToMe to (POSIX path of aliasPathToMe) as text
122  set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)
123  set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
124  set ocidPathToMeURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:(false)
125  set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent()
126  set ocidBinFilePathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:("bin/acextract") isDirectory:(false))
127  set strBinFilePath to ocidBinFilePathURL's |path| as text
128  #保存先 フォルダを別途作成して
129  set ocidAssetsDirPathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:("Assets") isDirectory:(true))
130  set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
131  ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
132  set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidAssetsDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
133  #
134  set strSaveDirPath to ocidAssetsDirPathURL's |path| as text
135  #アセットを書き出す
136  set strCommandText to ("\"" & strBinFilePath & "\" -i \"" & strFilePath & "\" -o \"" & strSaveDirPath & "\"") as text
137  log ("\r" & strCommandText & "\r") as text
138  set strExecCommand to ("/bin/zsh -c '" & strCommandText & "'") as text
139  try
140    set strResponse to (do shell script strExecCommand) as text
141    set boolNotExist to false as boolean
142  on error
143    log "zshでエラーになりました\r" & strCommandText & "\r"
144    set boolNotExist to true as boolean
145  end try
146  
147end if
148
149set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
150set boolDone to appSharedWorkspace's openURL:(ocidSaveDirPathURL)
151
AppleScriptで生成しました

|

スクリプト またはアプリケーション自身にアイコンを付与する


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# 書き出し からアプリケーションで保存してください
004# 何に使うのか?まったく理解できていないが…笑
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014
015################################
016#Path to me
017set aliasPathToMe to (path to me) as alias
018set strPathToMe to (POSIX path of aliasPathToMe) as text
019set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)
020set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
021set ocidPathToMeURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:(false)
022
023
024################
025#パス
026set strIconFilePath to ("/System/Applications/Mail.app/Contents/Resources/SidebarSent-selected.icns") as text
027set ocidIconFilePathStr to refMe's NSString's stringWithString:(strIconFilePath)
028set ocidIconFilePath to ocidIconFilePathStr's stringByStandardizingPath()
029set ocidIconFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidIconFilePath) isDirectory:false)
030
031################################
032#NSData's
033set ocidOption to (refMe's NSDataReadingMappedIfSafe)
034set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidIconFilePathURL) options:(ocidOption) |error| :(reference)
035if (item 2 of listResponse) = (missing value) then
036  log "正常処理"
037  set ocidReadData to (item 1 of listResponse)
038else if (item 2 of listResponse) ≠ (missing value) then
039  set strErrorNO to (item 2 of listDone)'s code() as text
040  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
041  refMe's NSLog("■:" & strErrorNO & strErrorMes)
042  return "エラーしました" & strErrorNO & strErrorMes
043end if
044
045################################
046#NSImage's
047set ocidReadImage to refMe's NSImage's alloc()'s initWithData:(ocidReadData)
048
049################################
050#ICon
051set appWorkspace to refMe's NSWorkspace's sharedWorkspace()
052set ocidOption to (refMe's NSExclude10_4ElementsIconCreationOption)
053set boolDone to (appWorkspace's setIcon:(ocidReadImage) forFile:(ocidPathToMe) options:(ocidOption))
054if boolDone is true then
055  log "正常処理"
056else if boolDone is false then
057  return "エラーしました"
058end if
AppleScriptで生成しました

|

【ICON】フォルダに画像を貼ったアイコンを生成する(v2)

こんな感じのフォルダアイコンを作成します
20240621073303514x328
AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004# V1 Aug 13, 2023
005# V2 2024 06 21 HEICの表示の回転Orientationに対応
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "CoreImage"
010use framework "AppKit"
011use scripting additions
012
013property refMe : a reference to current application
014
015on run
016  #デフォルトロケーション
017  set appFileManager to refMe's NSFileManager's defaultManager()
018  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
019  set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
020  set aliasPicturesDirPath to (ocidPicturesDirPathURL's absoluteURL()) as alias
021  #ダイアログを前面に出す
022  set strName to (name of current application) as text
023  if strName is "osascript" then
024    tell application "Finder" to activate
025  else
026    tell current application to activate
027  end if
028  #ダイアログ
029  set listUTI to {"public.png", "public.jpeg", "public.image"}
030  set strMes to ("画像ファイルを選んでください") as text
031  set strPrompt to ("画像ファイルを選んでください") as text
032  try
033    set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasPicturesDirPath of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
034    if listAliasFilePath is {} then
035      return "選んでください"
036    end if
037  on error
038    return "エラーしました"
039  end try
040  open listAliasFilePath
041end run
042
043on open listAliasFilePath
044  ########################
045  #フォルダイメージの保存先
046  set appFileManager to refMe's NSFileManager's defaultManager()
047  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
048  set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
049  set ocidSaveDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/Icons_Folder") isDirectory:(true)
050  
051  ########################
052  #ドロップされた場合のファイル判定OKの場合の格納用リスト
053  set ocidImageFileArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
054  #ドロップされたファイルを順番に
055  repeat with itemAliasFilePath in listAliasFilePath
056    #パス
057    set strFilePath to (POSIX path of itemAliasFilePath) as text
058    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
059    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
060    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
061    #UTIの取得
062    set listResponse to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error| :(reference))
063    if (item 1 of listResponse) = (true) then
064      log "getResourceValue 正常処理"
065      set ocidUTType to (item 2 of listResponse)
066    else if (item 3 of listResponse) ≠ (missing value) then
067      log (item 3 of listResponse)'s code() as text
068      log (item 3 of listResponse)'s localizedDescription() as text
069      return "getResourceValue エラーしました"
070    end if
071    #UTIの親構造まで全部のリスト
072    set ocidParentUTIArray to (ocidUTType's supertypes())'s allObjects()
073    #比較用のUTI
074    set ocidUTIpng to (refMe's UTType's typeWithIdentifier:("public.image"))
075    #imageが含まれていればOK
076    set boolContain to (ocidParentUTIArray's containsObject:(ocidUTIpng))
077    if boolContain is true then
078      (ocidImageFileArray's addObject:(ocidFilePathURL))
079    end if
080  end repeat
081  ########################
082  #フォルダのアイコンを読み込み
083  (* ドロップレット用
084  set aliasPathToMe to (path to me) as alias
085  set strPathToMe to (POSIX path of aliasPathToMe) as text
086  set ocidPathToMeStr to (refMe's NSString's stringWithString:(strPathToMe))
087  set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
088  set ocidPathToMeURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:false)
089  #フォルダアイコンのパス(テスト環境)
090  set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent()
091  set ocidFolderIconFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("Contents/Resources/icns/FolderDark.icns") isDirectory:(false)
092  #コンパイル時はこちら
093  # set ocidFolderIconFilePathURL to ocidPathToMeURL's URLByAppendingPathComponent:("Contents/Resources/icns/FolderDark.icns") isDirectory:(false)
094  *)
095  ########################
096  #フォルダ色選択
097  set listGenericFolderIcon to {"ダーク通常", "ライト通常", "ダークサーチ", "ライトサーチ"} as list
098  #ダイアログを前面に出す
099  set strName to (name of current application) as text
100  if strName is "osascript" then
101    tell application "Finder" to activate
102  else
103    tell current application to activate
104  end if
105  try
106    set listResponse to (choose from list listGenericFolderIcon with title "選んでください" with prompt "元になるアイコンを選択" default items (item 1 of listGenericFolderIcon) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
107  on error
108    log "エラーしました"
109    return "エラーしました"
110  end try
111  if (item 1 of listResponse) is false then
112    return "キャンセルしました"
113  end if
114  set strResponse to (item 1 of listResponse) as text
115  if strResponse is "ダーク通常" then
116    set ocidGenericFolderIconPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GenericFolderIcon.iconset/FolderDark.icns") isDirectory:(false)
117  else if strResponse is "ライト通常" then
118    set ocidGenericFolderIconPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GenericFolderIcon.iconset/Folder.icns") isDirectory:(false)
119  else if strResponse is "ダークサーチ" then
120    set ocidGenericFolderIconPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GenericFolderIcon.iconset/SmartFolderDark.icns") isDirectory:(false)
121  else if strResponse is "ライトサーチ" then
122    set ocidGenericFolderIconPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GenericFolderIcon.iconset/SmartFolder.icns") isDirectory:(false)
123  else
124    set ocidGenericFolderIconPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:("Icons/GenericFolderIcon.iconset/FolderDark.icns") isDirectory:(false)
125  end if
126  
127  #フォルダアイコンがすでにあるか?確認
128  set ocidGenericFolderIconPath to ocidGenericFolderIconPathURL's |path|()
129  #アイコンファイルの有無
130  set boolDirExists to appFileManager's fileExistsAtPath:(ocidGenericFolderIconPath) isDirectory:(false)
131  if boolDirExists = true then
132    #アイコンファイルがあるのでこのまま処理する
133    set ocidFolderIconFilePathURL to ocidGenericFolderIconPathURL
134  else if boolDirExists = false then
135    #アイコンファイルが無いので作る
136    #フォルダアイコンの取得
137    set boolDone to doMakeGenericFolderIcon()
138    if boolDone is false then
139      return "OSデフォルトのフォルダアイコンの取得に失敗しました"
140    else if boolDone is true then
141      set ocidFolderIconFilePathURL to ocidGenericFolderIconPathURL
142    end if
143  end if
144  ########################
145  #処理開始
146  #読み込みNSDATA
147  set ocidOption to (refMe's NSDataReadingMappedIfSafe)
148  set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFolderIconFilePathURL) options:(ocidOption) |error| :(reference)
149  if (item 2 of listResponse) = (missing value) then
150    log "正常処理"
151    set ocidFolderIconData to (item 1 of listResponse)
152  else if (item 2 of listResponse) ≠ (missing value) then
153    log (item 2 of listResponse)'s code() as text
154    log (item 2 of listResponse)'s localizedDescription() as text
155    return "エラーしました"
156  end if
157  #NSDATAをNSIMAGEに
158  set ocidFolderIconImage to refMe's NSImage's alloc()'s initWithData:(ocidFolderIconData)
159  #representations
160  set ocidImageRepArray to ocidFolderIconImage's representations()
161  set ocidFolderImgRep to ocidImageRepArray's firstObject()
162  #解像度を72ppiにしておく
163  #ピクセルサイズを取得
164  set ocidPixelsHigh to ocidFolderImgRep's pixelsHigh()
165  set ocidPixelsWide to ocidFolderImgRep's pixelsWide()
166  #サイズにして
167  set ocidSetSize to refMe's NSSize's NSMakeSize(ocidPixelsWide, ocidPixelsWide)
168  #72ppi=ピクセルサイズと同じポイントサイズにする
169  ocidFolderImgRep's setSize:(ocidSetSize)
170  ########################
171  #ドロップされた画像を順番に処理する
172  repeat with itemImageFileURL in ocidImageFileArray
173    #ドロップされた画像のファイル名
174    set ocidFileName to itemImageFileURL's lastPathComponent()
175    set ociBaseFileName to ocidFileName's stringByDeletingPathExtension()
176    ########################
177    #フォルダを作っておく
178    set ocidSaveFolderPathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ociBaseFileName) isDirectory:(true))
179    #フォルダを作っておく
180    set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
181    (ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions))
182    set listDone to (appFileManager's createDirectoryAtURL:(ocidSaveFolderPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference))
183    if (item 1 of listDone) is true then
184      log "正常処理"
185    else if (item 2 of listDone) ≠ (missing value) then
186      log (item 2 of listDone)'s code() as text
187      log (item 2 of listDone)'s localizedDescription() as text
188      return "エラーしました"
189    end if
190    ########################
191    ##ここでアイコンのサイズ決めている
192    # set numWidth to 512 as integer
193    # set numHight to 512 as integer
194    set numWidth to ocidPixelsWide as integer
195    set numHight to ocidPixelsHigh as integer
196    #ドロップされた画像の読み込み
197    #読み込みNSDATA
198    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
199    set listResponse to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemImageFileURL) options:(ocidOption) |error| :(reference))
200    if (item 2 of listResponse) = (missing value) then
201      log "正常処理"
202      set ocidImageData to (item 1 of listResponse)
203    else if (item 2 of listResponse) ≠ (missing value) then
204      log (item 2 of listResponse)'s code() as text
205      log (item 2 of listResponse)'s localizedDescription() as text
206      return "エラーしました"
207    end if
208    ########################
209    #CIimage
210    set ocidAddImageCI to (refMe's CIImage's imageWithData:(ocidImageData) options:(missing value))
211    #ファイルのサイズを調べる
212    set ocidCGRect to ocidAddImageCI's extent()
213    #縦横の値を取得
214    set numImageWidth to refMe's CGRectGetWidth(ocidCGRect) as number
215    set numImageHeight to refMe's CGRectGetHeight(ocidCGRect) as number
216    if numImageWidth < numImageHeight then
217      set numResizeScale to (numWidth / numImageHeight)
218    else
219      #リサイズする指数
220      set numResizeScale to (numWidth / numImageWidth)
221    end if
222    ########################
223    #HEICの回転対応
224    #メタデータ取得
225    set ocidOripertesDict to ocidAddImageCI's |properties|()
226    set ocidOrientation to (ocidOripertesDict's valueForKey:("Orientation"))
227    #Orientationの値が無い=通常画像
228    if ocidOrientation = (missing value) then
229      set strOrientation to ("1") as text
230    else
231      #IF文用にテキストにしておく
232      set strOrientation to (ocidOrientation) as text
233    end if
234    #Transform指定
235    #Orientationの値に応じてimageTransformForOrientationを指定しておく
236    if strOrientation is "1" then
237      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationUp))
238    else if strOrientation is "2" then
239      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationUpMirrored))
240    else if strOrientation is "3" then
241      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationDown))
242    else if strOrientation is "4" then
243      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationDownMirrored))
244    else if strOrientation is "5" then
245      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationLeftMirrored))
246    else if strOrientation is "6" then
247      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationRight))
248    else if strOrientation is "7" then
249      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationRightMirrored))
250    else if strOrientation is "8" then
251      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationLeft))
252    else
253      set recordCiImageData to (ocidAddImageCI's imageTransformForOrientation:(refMe's kCGImagePropertyOrientationUp))
254    end if
255    
256    ########################
257    #Transform適応
258    set ocidCIImageData to (ocidAddImageCI's imageByApplyingTransform:recordCiImageData)
259    ####Parameters
260    set recordParameters to {inputImage:ocidCIImageData, inputScale:numResizeScale, inputAspectRatio:1.0} as record
261    ####リサイズする指数でリサイズ
262    set ocidCiFilterData to (refMe's CIFilter's filterWithName:"CILanczosScaleTransform" withInputParameters:(recordParameters))
263    #####リサイズ済みイメージ
264    set ocidResizedCiImage to ocidCiFilterData's outputImage()
265    #####NSBitmapImageRepに変換して
266    set ocidResizedImagePep to (refMe's NSBitmapImageRep's alloc()'s initWithCIImage:(ocidResizedCiImage))
267    if (strOrientation as integer) > 4 then
268      set numResizedWide to ocidResizedImagePep's pixelsHigh()
269      set numResizedHigh to ocidResizedImagePep's pixelsWide()
270    else
271      set numResizedHigh to ocidResizedImagePep's pixelsHigh()
272      set numResizedWide to ocidResizedImagePep's pixelsWide()
273    end if
274    if numImageWidth < numImageHeight then
275      set numOffSetW to ((numResizedHigh - numResizedWide) / 2) as integer
276      set numOffSetH to 0 as integer
277    else
278      set numOffSetH to ((numResizedWide - numResizedHigh) / 2) as integer
279      set numOffSetW to 0 as integer
280    end if
281    
282    ########################
283    #出力イメージ NSBitmapImageRep's
284    set ocidSetColor to (refMe's NSColor's colorWithDeviceRed:0 green:0 blue:0 alpha:1)
285    set ocidBitmapFormat to refMe's NSBitmapFormatAlphaFirst
286    set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
287    set ocidNSBitmapImageFileType to refMe's NSBitmapImageFileTypeTIFF
288    set ocidBitmapImageRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numWidth) pixelsHigh:(numHight) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
289    ###初期化
290    refMe's NSGraphicsContext's saveGraphicsState()
291    (refMe's NSGraphicsContext's setCurrentContext:(refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:ocidBitmapImageRep))
292    ####画像作成終了
293    refMe's NSGraphicsContext's restoreGraphicsState()
294    ########################
295    #フォルダのイメージを重ねる
296    #NSGraphicsContext's
297    refMe's NSGraphicsContext's saveGraphicsState()
298    ###生成された画像でNSGraphicsContext初期化
299    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidBitmapImageRep))
300    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
301    #
302    set ocidSetOrigin to refMe's NSPoint's NSMakePoint(0, 0)
303    set ocidSetSize to refMe's NSMakeSize's NSMakeSize(numWidth, numHight)
304    set ocidFromRect to refMe's NSRect's NSMakeRect((ocidSetOrigin's x()), (ocidSetOrigin's y()), (ocidSetSize's width()), (ocidSetSize's height()))
305    set ocidDrawRect to ocidFromRect
306    #この記述でも充分
307    #set ocidFromRect to {origin:{x:0, y:0}, |size|:{width:numWidth, height:numHight}} as list
308    #set ocidDrawRect to {origin:{x:0, y:0}, |size|:{width:numWidth, height:numHight}} as list
309    ####フォルダ画像を背景画像上に配置する
310    set ocidOption to (refMe's NSCompositingOperationSourceOver)
311    set boolDone to (ocidFolderImgRep's drawInRect:(ocidDrawRect) fromRect:(ocidFromRect) operation:(ocidOption) fraction:1.0 respectFlipped:true hints:(missing value))
312    if boolDone is false then
313      return "画像の合成に失敗しました"
314    end if
315    ####画像作成終了
316    refMe's NSGraphicsContext's restoreGraphicsState()
317    ########################
318    #ドロップシャドウ生成
319    set ocidShadow to refMe's NSShadow's alloc()'s init()
320    set ocidShadowColor to (refMe's NSColor's colorWithDeviceRed:0 green:0 blue:0 alpha:0.5)
321    (ocidShadow's setShadowColor:(ocidShadowColor))
322    (ocidShadow's setShadowBlurRadius:(4))
323    set ocidShadowSize to refMe's NSMakeSize(3, -3)
324    (ocidShadow's setShadowOffset:(ocidShadowSize))
325    ########################
326    #フォルダの上にアイコン画像を重ねる
327    #NSGraphicsContext's
328    refMe's NSGraphicsContext's saveGraphicsState()
329    ###生成された画像でNSGraphicsContext初期化
330    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidBitmapImageRep))
331    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
332    set ocidFromRect to {origin:{x:0, y:0}, |size|:{width:numWidth, Hight:numHight}}
333    #HEICの位置合わせは出物あわせで根拠が無い…汗
334    if (strOrientation as integer) > 4 then
335      set numXoffSet to (256 + (numOffSetH / 2)) as integer
336      set numYoffSet to (220 + numOffSetW) as integer
337    else
338      set numXoffSet to (256 + (numOffSetW / 2)) as integer
339      set numYoffSet to (220 + numOffSetH) as integer
340    end if
341    #フォルダアイコン画像の半分の縦横サイズで
342    #指定のオフセット位置に描画する
343    set ocidSetOrigin to refMe's NSPoint's NSMakePoint(numXoffSet, numYoffSet)
344    set ocidSetSize to refMe's NSMakeSize's NSMakeSize((numWidth / 2), (numHight / 2))
345    set ocidSetRect to refMe's NSRect's NSMakeRect((ocidSetOrigin's x()), (ocidSetOrigin's y()), (ocidSetSize's width()), (ocidSetSize's height()))
346    #この記述でもOKだった
347    # set recordDrawRect to {origin:{x:(numXoffSet), y:(numYoffSet)}, |size|:{width:(numWidth / 2), height:(numHight / 2)}} as record
348    ###コマ画像を背景画像上に配置する
349    set ocidOption to (refMe's NSCompositingOperationSourceOver)
350    ###ドロップシャドウ適応
351    ocidShadow's |set|()
352    set boolDone to (ocidResizedImagePep's drawInRect:(ocidSetRect) fromRect:(ocidFromRect) operation:(ocidOption) fraction:1.0 respectFlipped:true hints:(missing value))
353    if boolDone is false then
354      return "画像の合成に失敗しました"
355    end if
356    ####画像作成終了
357    refMe's NSGraphicsContext's restoreGraphicsState()
358    
359    ########################
360    #出力用にTIFFに変換する
361    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
362    ####TIFF用の圧縮プロパティ(NSImageCompressionFactor)
363    (ocidPropertyDict's setObject:0 forKey:(refMe's NSImageCompressionFactor))
364    ####インラインデータに変換
365    set ocidType to (refMe's NSBitmapImageFileTypeTIFF)
366    set ocidTiffData to (ocidBitmapImageRep's representationUsingType:(ocidType) |properties|:(ocidPropertyDict))
367    #保存先パス
368    set ocidSaveImgFilePathURL to (ocidSaveFolderPathURL's URLByAppendingPathComponent:(ociBaseFileName) isDirectory:(false))
369    set ocidTiffPathURL to (ocidSaveImgFilePathURL's URLByAppendingPathExtension:("tiff"))
370    set ocidOption to (refMe's NSDataWritingAtomic)
371    set listDone to (ocidTiffData's writeToURL:(ocidTiffPathURL) options:(ocidOption) |error| :(reference))
372    if (item 1 of listDone) is true then
373      log "正常処理"
374    else if (item 2 of listDone) ≠ (missing value) then
375      log (item 2 of listDone)'s code() as text
376      log (item 2 of listDone)'s localizedDescription() as text
377      return "エラーしました"
378    end if
379    
380    ########################
381    #出力用にPNGに変換する
382    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
383    (ocidPropertyDict's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
384    (ocidPropertyDict's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
385    #変換
386    set ocidType to (refMe's NSBitmapImageFileTypePNG)
387    set ocidPngData to (ocidBitmapImageRep's representationUsingType:(ocidType) |properties|:(ocidPropertyDict))
388    #保存先パス
389    set ocidSaveImgFilePathURL to (ocidSaveFolderPathURL's URLByAppendingPathComponent:(ociBaseFileName) isDirectory:(false))
390    set ocidPngPathURL to (ocidSaveImgFilePathURL's URLByAppendingPathExtension:("png"))
391    set ocidOption to (refMe's NSDataWritingAtomic)
392    set listDone to (ocidPngData's writeToURL:(ocidPngPathURL) options:(ocidOption) |error| :(reference))
393    if (item 1 of listDone) is true then
394      log "正常処理"
395    else if (item 2 of listDone) ≠ (missing value) then
396      log (item 2 of listDone)'s code() as text
397      log (item 2 of listDone)'s localizedDescription() as text
398      return "エラーしました"
399    end if
400    
401    ########################
402    #アイコン用にPNGイメージをNSIMAGEに
403    set ocidAddIconImageData to (refMe's NSImage's alloc()'s initWithData:(ocidPngData))
404    ########################
405    #アイコンを付与する
406    set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
407    set ocidSaveFolderPath to ocidSaveFolderPathURL's |path|()
408    ###アイコン付与
409    set ocidOption to (refMe's NSExclude10_4ElementsIconCreationOption)
410    set boolDone to (appSharedWorkspace's setIcon:(ocidAddIconImageData) forFile:(ocidSaveFolderPath) options:(ocidOption))
411    if boolDone is true then
412      log "正常処理"
413    else if boolDone is false then
414      return "エラーしました"
415    end if
416  end repeat
417  
418  ##保存先を開く
419  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
420  appSharedWorkspace's activateFileViewerSelectingURLs:({ocidSaveFolderPathURL})
421  
422end open
423
424####################################
425#OSデフォルトのアイコンイメージを取得
426to doMakeGenericFolderIcon()
427  #作成するフォルダのアクセス権
428  set appFileManager to refMe's NSFileManager's defaultManager()
429  set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
430  (ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions))
431  
432  #Assets.carのパス
433  set strCarFilePath to ("/System/Library/PrivateFrameworks/IconFoundation.framework/Versions/A/Resources/Assets.car") as text
434  set ocidCarFilePath to refMe's NSString's stringWithString:(strCarFilePath)
435  set ocidCarFilePathURL to refMe's NSURL's fileURLWithPath:(ocidCarFilePath)
436  set ocidFileName to ocidCarFilePathURL's lastPathComponent()
437  
438  #Classは4種類
439  set listFolderName to {"FolderDark", "SmartFolder", "Folder", "SmartFolderDark"} as list
440  #4種類全部ICNSを生成する
441  repeat with itemFolderName in listFolderName
442    ##########################
443    #CARファイルからiconsetを書き出す
444    #画像の保存先iconset
445    set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
446    set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
447    set strSubPath to ("Icons/GenericFolderIcon.iconset/" & itemFolderName & ".iconset") as text
448    set ocidIconsDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:(strSubPath))
449    #フォルダを作っておく
450    set listDone to (appFileManager's createDirectoryAtURL:(ocidIconsDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference))
451    if (item 1 of listDone) is true then
452      log "正常処理"
453    else if (item 2 of listDone) ≠ (missing value) then
454      log (item 2 of listDone)'s code() as text
455      log (item 2 of listDone)'s localizedDescription() as text
456      log "エラーしました"
457      return false
458    end if
459    #コマンド整形
460    set strIconFilePath to (ocidCarFilePathURL's |path|) as text
461    set strSaveDirPath to (ocidIconsDirPathURL's |path|) as text
462    set strCommandText to ("/usr/bin/iconutil --convert iconset \"" & strIconFilePath & "\" " & itemFolderName & " -o \"" & strSaveDirPath & "\"") as text
463    log strCommandText
464    #コマンド実行
465    try
466      do shell script strCommandText
467    on error
468      log "コマンドでエラーしました"
469      return false
470    end try
471  end repeat
472  ##########################
473  #iconsetからicnsファイルを作成
474  #パス
475  set strSubPath to ("Icons/GenericFolderIcon.iconset") as text
476  set ocidIconsDirPathURL to ocidPicturesDirPathURL's URLByAppendingPathComponent:(strSubPath)
477  set ocidDistIconFilePathURL to ocidIconsDirPathURL's URLByAppendingPathComponent:(ocidFileName)
478  #Carファイルのコピーはしないことにする
479  #set listDone to appFileManager's copyItemAtURL:(ocidCarFilePathURL) toURL:(ocidDistIconFilePathURL) |error| :(reference)
480  #4種類全部作る
481  set listFolderName to {"FolderDark", "SmartFolder", "Folder", "SmartFolderDark"} as list
482  #4種類を順番に
483  repeat with itemFolderName in listFolderName
484    #パス
485    set strSubPath to ("Icons/GenericFolderIcon.iconset/" & itemFolderName & ".iconset") as text
486    set ocidIconsDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:(strSubPath))
487    set strFileNamePath to ("Icons/GenericFolderIcon.iconset/" & itemFolderName & ".icns") as text
488    set ocidSaveFilePathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:(strFileNamePath))
489    #コマンド整形
490    set strIconDirPath to (ocidIconsDirPathURL's |path|) as text
491    set strSaveFilePath to (ocidSaveFilePathURL's |path|) as text
492    set strCommandText to ("/usr/bin/iconutil --convert icns \"" & strIconDirPath & "\"  -o \"" & strSaveFilePath & "\"") as text
493    log strCommandText
494    #コマンド実行
495    try
496      do shell script strCommandText
497    on error
498      return false
499    end try
500  end repeat
501  #全部終了したらtrueを返す
502  return true
503  
504end doMakeGenericFolderIcon
AppleScriptで生成しました

|

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


AppleScript サンプルコード

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

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