AppleScript NSImage

画像のリサイズ(解像度72ppi換算)後にPNG保存する


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

############################
### 入力ダイアログ
############################
## クリップボードの中身取り出し
###初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
log "テキストなし"
    set strReadString to ("リサイズ後の『幅px』数値入力") as text
  end if
end if

###ダイアログを全面に
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasIconPath to (POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns") as alias
set strTitle to ("入力してください") as text
set strMes to ("リサイズ後の『幅px』数値入力") as text
set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)

if (gave up of recordResult) is true then
return "時間切れです"
else if (button returned of recordResult) is "キャンセル" then
return "キャンセルです"
else
  set strReturnedText to (text returned of recordResult) as text
end if
#戻り値の整形
set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
###タブと改行を除去しておく
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's appendString:(ocidResponseText)
##改行除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
##タブ除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
####戻り値を半角にする
set ocidNSStringTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
set ocidTextM to (ocidTextM's stringByApplyingTransform:ocidNSStringTransform |reverse|:false)
##カンマ置換
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:(",") withString:(".")
###数字以外の値を取る
set ocidDecSet to refMe's NSCharacterSet's decimalDigitCharacterSet
set ocidCharSet to ocidDecSet's invertedSet()
set ocidCharArray to ocidTextM's componentsSeparatedByCharactersInSet:ocidCharSet
set ocidInteger to ocidCharArray's componentsJoinedByString:""
#
set numNewPixelsWidth to ocidInteger as integer

############################
### ダイアログ
############################
set appFileManager to refMe's NSFileManager's defaultManager()
###デフォルトロケーション
set ocidUserDocumentPathArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopPathURL to ocidUserDocumentPathArray's firstObject()
set aliasDefaultLocation to (ocidDesktopPathURL's absoluteURL()) as alias
#####ダイアログを前面に
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
####ダイアログを出す
set listUTI to {"public.image"} as list
set listAliasFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles, showing package contents and multiple selections allowed) as list

############################
####選んだファイルパスの数だけ繰り返し
############################
repeat with itemAliasFilePath in listAliasFilePath
  ##入力パス
  set strFilePath to (POSIX path of itemAliasFilePath) as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
  ###########################
  ###【1】元イメージ
  ###読み込むイメージURL
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
  ##NSIMAGEに読み込む
  set ocidReadImage to (refMe's NSImage's alloc()'s initWithContentsOfURL:(ocidFilePathURL))
  set ocidNsImageSize to ocidReadImage's |size|()
  set numPtWidth to ocidNsImageSize's width
  set numPtHeigh to ocidNsImageSize's height
log numPtWidth as integer
log numPtHeigh as integer
  ##BitMapRepに変換
  set ocidReadImageRepArray to ocidReadImage's representations()
  set ocidReadImageRep to (ocidReadImageRepArray's objectAtIndex:0)
  ##ピクセルサイズ取得
  set numPixelsWidth to ocidReadImageRep's pixelsWide()
  set numPixelsHeight to ocidReadImageRep's pixelsHigh()
  ##まずは72ppiにする
  set ocidPixelsSize to refMe's NSMakeSize(numPixelsWidth, numPixelsHeight)
(ocidReadImageRep's setSize:(ocidPixelsSize))
  ###########################
  ###【2】出力イメージ
  ###サイズ計算
  ### 画像サイズ変更比率=出力ピクセルサイズ縦➗読み込み画像ピクセルサイズ縦
  set numImageVW to numNewPixelsWidth / numPixelsWidth as number
  ###同じ比率で横幅を計算 読み込み画像ピクセルサイズ横×画像サイズ変更比率
  set numNewPixelsHeight to numPixelsHeight * numImageVW as integer
  ###↑で計算した出力用の画像ピクセルサイズ
  set ocidNewImagePixelsSize to refMe's NSMakeSize(numNewPixelsWidth, numNewPixelsHeight)
  ###
  ###Retinaモニター時 ポイントサイズ=pixの半分
  set intResPer to (144 / 72) as number
  set intNewWidth to (numNewPixelsWidth / intResPer) as integer
  set intNewHeight to (numNewPixelsHeight / intResPer) as integer
  set ocidNewImageSize to refMe's NSMakeSize(intNewWidth, intNewHeight)
  set ocidNewRect to refMe's NSMakeRect(0, 0, intNewWidth, intNewHeight)
  
  ###出力用イメージ NSBitmapImageRep
  # samplesPerPixel
  set intSPP to 4 as integer
  # bitsPerSample
  set intBPS to 8 as integer
  # bytesPerRow
  set intBPR to (numNewPixelsWidth * intSPP) as integer
  # bitsPerPixel
  set intBPP to 32 as integer
  # RGB系のカラースペース
  set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
  # アルファあり
  set ocidBitmapFormat to refMe's NSAlphaFirstBitmapFormat
  ##出力ピクセルサイズのブランクイメージ
  set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numNewPixelsWidth) pixelsHigh:(numNewPixelsHeight) bitsPerSample:(intBPS) samplesPerPixel:(intSPP) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(intBPR) bitsPerPixel:(intBPP))
  
  ###########################
  ###【3】ArtBord
  ### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
  ###Context
  set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
  ###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
  ##色を個別に指定する場合 値は0が暗 1が明
  set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1.0) green:(1.0) blue:(1.0) alpha:(0.0))
ocidSetColor's |set|()
  ###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numNewPixelsWidth), height:(numNewPixelsHeight)}})
  ####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
  
  ###########################
  ###【3】合成 リザイスでNSCompositeSourceOver
  ### 初期化
refMe's NSGraphicsContext's saveGraphicsState()
  ###Context
  set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
  ###NSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
  ####NSCompositeSourceOver
  set ocidDrawInRect to {origin:{x:(0), y:(0)}, |size|:{width:(numNewPixelsWidth), Hight:(numNewPixelsHeight)}}
  set ocidFromRect to (refMe's NSZeroRect)
  set ocidOption to (refMe's NSCompositeSourceOver)
  ## set ocidOption to (refMe's NSCompositeCopy)
(ocidReadImageRep's drawInRect:(ocidDrawInRect) fromRect:(ocidFromRect) operation:(ocidOption) fraction:1.0 respectFlipped:true hints:(missing value))
  ####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
  
  ###########################
  ###【5】保存
  ####保存オプション
  set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
(ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
  
  ###保存は別ディレクトリに
  set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  set ocidFileName to ocidFilePathURL's lastPathComponent()
  #フォルダを作って
  set strSaveDirName to ("_ResizedImage") as text
  set ocidSaveDirPathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:(strSaveDirName))
  set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
  # 777-->511 755-->493 700-->448 766-->502
(ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions))
  set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
  #保存先パス
  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidFileName))
  ##保存
  set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
  set boolDone to (ocidNSInlineData's writeToURL:(ocidSaveFilePathURL) atomically:true)
  
  set ocidReadImageRep to ""
  set ocidArtBoardRep to ""
end repeat


|

画像の解像度だけ変更する


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "Quartz"
use framework "CoreImage"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

on run
  
  set aliasIconPass to (POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MultipleItemsIcon.icns") as alias
  set strDialogText to "ドロップしても利用できます"
  set strTitleText to "画像ファイルを選んでください"
  set listButton to {"ファイルを選びます", "キャンセル"} as list
display dialog strDialogText buttons listButton default button 1 cancel button 2 with title strTitleText with icon aliasIconPass giving up after 2 with hidden answer
  
  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
  set listChooseFileUTI to {"public.png", "public.jpeg"}
  set strPromptText to "イメージファイルを選んでください" as text
  set strPromptMes to "イメージファイルを選んでください" as text
  set listAliasFilePath to (choose file strPromptMes with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with showing package contents, invisibles and multiple selections allowed) as list
  
  -->値をOpenに渡たす
open listAliasFilePath
end run


on open listAliasFilePath
  ##########################
  ####解像度を指定する
  ##########################
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  #
  set listResolution to {"72", "96", "120", "144", "216", "288", "300", "360"} as list
  #
  try
    set listResponse to (choose from list listResolution with title "選んでください" with prompt "解像度を選んでください" default items (item 1 of listResolution) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
  on error
log "エラーしました"
return "エラーしました"
  end try
  if (item 1 of listResponse) is false then
return "キャンセルしました"
  end if
  set strResolution to (item 1 of listResponse) as text
  set numResolution to strResolution as integer
  
  ##########################
  ####ファイルの数だけ繰り返し
  ##########################
  set ocidFalse to (refMe's NSNumber's numberWithBool:false)'s boolValue
  set ocidTrue to (refMe's NSNumber's numberWithBool:true)'s boolValue
  repeat with itemAliasFilePath in listAliasFilePath
    ####まずはUNIXパスにして
    set strFilePath to (POSIX path of itemAliasFilePath) as text
    set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
    ####ファイル名を取得
    set ocidFileName to ocidFilePathURL's lastPathComponent()
    ####ファイル名から拡張子を取っていわゆるベースファイル名を取得
    set strPrefixName to ocidFileName's stringByDeletingPathExtension as text
    ####コンテナディレクトリを取得
    set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
    ###拡張子を取得して小文字にしておく
    set ocidExtensionName to ocidFilePathURL's pathExtension()
    set ocidExtensionNameLowCase to ocidExtensionName's lowercaseString()
    set strExtensionName to ocidExtensionNameLowCase as text
    #####################
    #### 本処理
    #####################
    ####データ読み込み
    set ocidImageData to (refMe's NSImage's alloc()'s initWithContentsOfURL:ocidFilePathURL)
    set ocidImageDataSize to ocidImageData's |size|()
    set numPointWidth to width of ocidImageDataSize
    set numPointHeight to height of ocidImageDataSize
    ####ImageRepに変換
    set ocidImageRepArray to ocidImageData's representations()
    ####サイズと解像度計算
    set ocidImageRep to (ocidImageRepArray's objectAtIndex:0)
    #プロパティを保存時用に取得
    set ocidPropertiesArray to ocidImageRep's |properties|
    #ピクセルサイズを取得
    set numPixelsWidth to ocidImageRep's pixelsWide()
    set numPixelsHeight to ocidImageRep's pixelsHigh()
    #サイズセットする比率
    set numSetResolution to (numResolution / 72.0) as number
    # ピクセルサイズに↑の比率で割って セットするポイントサイズ
    set numNewImageWidth to (numPixelsWidth / numSetResolution) as number
    set numNewImageHeight to (numPixelsHeight / numSetResolution) as number
    #####リサイズの値レコード
    set recordNewImageSize to {width:numNewImageWidth, height:numNewImageHeight} as record
    ###リサイズ
(ocidImageRep's setSize:(recordNewImageSize))
    #拡張子による分岐
    if strExtensionName is "png" then
      ###展開 PNG
      set ocidSaveImageType to refMe's NSBitmapImageFileTypePNG
      set ocidNewImageData to (ocidImageRep's representationUsingType:ocidSaveImageType |properties|:(ocidPropertiesArray))
    else if strExtensionName is "jpg" then
      ###展開 JPEG
      set ocidSaveImageType to refMe's NSBitmapImageFileTypeJPEG
      set ocidNewImageData to (ocidImageRep's representationUsingType:ocidSaveImageType |properties|:(ocidPropertiesArray))
    else if strExtensionName is "jpeg" then
      set ocidSaveImageType to refMe's NSBitmapImageFileTypeJPEG
      set ocidNewImageData to (ocidImageRep's representationUsingType:ocidSaveImageType |properties|:(ocidPropertiesArray))
    else
log "処理しないでそのまま保存"
    end if
    ###上書き保存
    set boolResults to (ocidNewImageData's writeToURL:ocidFilePathURL atomically:true)
    #結果
    if boolResults is true then
log "処理OK"
    else
log "処理NGなのでそのままにする"
log "失敗ラベル赤を塗る"
      set boolResults to (ocidImagFilePathURL's setResourceValue:6 forKey:(refMe's NSURLLabelNumberKey) |error|:(reference))
    end if
    set ocidImageData to ""
    set ocidImageRep to ""
    set ocidNewImageData to ""
  end repeat
end open


|

[NSImage]画像の解像度変更

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# 
#                    書き出しから アプリケーションにしてください
#
#                       com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL

property boolFileChk : true
property boolFolderChk : false
property listUTI : {"public.png", "public.jpeg"}
####指定解像度ppi
property numResolution : 72

on run
    set objFileManager to refMe's NSFileManager's defaultManager()
    set ocidGetUrlArray to (objFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
    set ocidDesktopDirPathURL to ocidGetUrlArray's objectAtIndex:0
    set aliasDesktopDirPath to ocidDesktopDirPathURL as alias
    ####ダイアログ
    set listFilePathAlias to (choose file with prompt "ファイルを選んでください" default location aliasDesktopDirPath of type listUTI with multiple selections allowed and showing package contents without invisibles) as list
    open listFilePathAlias
end run


on open listFilePathAlias
    ##ファイルマネージャー起動
    set objFileManager to refMe's NSFileManager's defaultManager()
    ##繰り返しのはじまり
    repeat with itemFilePathAlias in listFilePathAlias
        
        
        
        set strFilePath to POSIX path of itemFilePathAlias as text
        set ocidFilePath to (refNSString's stringWithString:strFilePath)
        set ocidFilePathURL to (refNSURL's alloc()'s initFileURLWithPath:ocidFilePath)
        ####拡張子を取得
        set ocidFileExtension to ocidFilePathURL's pathExtension()
        set ocidFileExtension to ocidFileExtension's lowercaseString()
        set strFileExtension to ocidFileExtension as text
        ####データ読み込み
        set ocidImageData to (refMe's NSImage's alloc()'s initWithContentsOfURL:ocidFilePathURL)
        ####set ocidImageSize to ocidImageData's |size|()
        set ocidImageRepArray to ocidImageData's representations()
        set ocidImageRep to (ocidImageRepArray's objectAtIndex:0)
        set numpixelsWidth to ocidImageRep's pixelsWide()
        set numpixelsHeight to ocidImageRep's pixelsHigh()
        set ocidImageRepSize to ocidImageRep's |size|()
        set numPointWidth to width of ocidImageRepSize
        set numPointHeight to height of ocidImageRepSize
        set numCurrentDPI to ((numResolution * numpixelsWidth) / numPointWidth) as integer
        set numNewImageWidth to ((numResolution * numpixelsWidth) / numResolution)
        set numNewImageHeight to ((numResolution * numpixelsHeight) / numResolution)
        #####リサイズして-->この場合、ピクセル数そのままサイズ変更=解像度が変わる
        set recordNewImageSize to {width:numNewImageWidth, height:numNewImageHeight} as record
        (ocidImageRep's setSize:recordNewImageSize)
        ###展開
        if strFileExtension is "png" then
            set ocidSaveImageType to refMe's NSBitmapImageFileTypePNG
            set recordPngProperties to {NSImageInterlaced:true, NSImageDitherTransparency:true}
            set ocidNewImageData to (ocidImageRep's representationUsingType:ocidSaveImageType |properties|:recordPngProperties)
        else if strFileExtension is "jpeg" then
            set ocidSaveImageType to refMe's NSBitmapImageFileTypeJPEG
            set ocidBackGroundColor to (refMe's NSColor's colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:1.0)
            set recordJpgProperties to {NSImageCompressionFactor:1.0, NSImageProgressive:false, NSImageFallbackBackgroundColor:ocidBackGroundColor}
            set ocidNewImageData to (ocidImageRep's representationUsingType:ocidSaveImageType |properties|:recordJpgProperties)
        else if strFileExtension is "jpg" then
            set ocidSaveImageType to refMe's NSBitmapImageFileTypeJPEG
            set ocidBackGroundColor to (refMe's NSColor's colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:1.0)
            set recordJpgProperties to {NSImageCompressionFactor:1.0, NSImageProgressive:false, NSImageFallbackBackgroundColor:ocidBackGroundColor}
            set ocidNewImageData to (ocidImageRep's representationUsingType:ocidSaveImageType |properties|:recordJpgProperties)
            
        end if
        
        ###上書き保存
        set boolResults to (ocidNewImageData's writeToURL:ocidFilePathURL atomically:true)
        set ocidImageRep to ""
        set ocidNewImageData to ""
        set ocidImageData to ""
        
        
        ##繰り返しの終わり
    end repeat
end open


|

[NSimage] イメージデータをPDFに変換

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL
property refNSImage : a reference to refMe's NSImage
property refPDFDocument : a reference to refMe's PDFDocument
property refPDFPage : a reference to refMe's PDFPage

###################################
#####ダイアログ
###################################a
tell application "Finder"
##set aliasDefaultLocation to container of (path to me) as alias
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
set listChooseFileUTI to {"public.image"}
set strPromptText to "ファイルを選んでください" as text
set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and showing package contents without multiple selections allowed) as list
###################################
#####パス処理
###################################
###エリアス
set aliasFilePath to item 1 of listAliasFilePath as alias
###UNIXパス
set strFilePath to POSIX path of aliasFilePath as text
###String
set ocidFilePath to refNSString's stringWithString:strFilePath
###NSURL
set ocidFilePathURL to refNSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false
####ファイル名を取得
set ocidFileName to ocidFilePathURL's lastPathComponent()
####拡張子を取得
set ocidFileExtension to ocidFilePathURL's pathExtension()
####ファイル名から拡張子を取っていわゆるベースファイル名を取得
set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
####コンテナディレクトリ
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()


###################################
#####保存ダイアログ
###################################
###ファイル名
set strPrefixName to ocidPrefixName as text
###拡張子
###同じ拡張子の場合
##set strFileExtension to ocidFileExtension as text
###拡張子変える場合
set strFileExtension to "pdf"
###ダイアログに出すファイル名
set strDefaultName to (strPrefixName & ".output." & strFileExtension) as text
set strPromptText to "名前を決めてください"
###選んだファイルの同階層をデフォルトの場合
set aliasDefaultLocation to ocidContainerDirPathURL as alias
####デスクトップの場合
##set aliasDefaultLocation to (path to desktop folder from user domain) as alias
####ファイル名ダイアログ
####実在しない『はず』なのでas «class furl»
set aliasSaveFilePath to (choose file name default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
####UNIXパス
set strSaveFilePath to POSIX path of aliasSaveFilePath as text
####ドキュメントのパスをNSString
set ocidSaveFilePath to refNSString's stringWithString:strSaveFilePath
####ドキュメントのパスをNSURL
set ocidSaveFilePathURL to refNSURL's fileURLWithPath:ocidSaveFilePath
###拡張子取得
set strFileExtensionName to ocidSaveFilePathURL's pathExtension() as text
###ダイアログで拡張子を取っちゃった時対策
if strFileExtensionName is not strFileExtension then
set ocidSaveFilePathURL to ocidSaveFilePathURL's URLByAppendingPathExtension:strFileExtension
end if



###################################
#####本処理
###################################

###イメージファイルを読み込み
set ocidNsImage to refNSImage's alloc()'s initWithContentsOfURL:ocidFilePathURL

####PDFドキュメント初期化
set ocidPdfActivDoc to refPDFDocument's alloc()'s init()

###読み込んだイメージをPDFのページとして初期化
set ocidPdfPage to refPDFPage's alloc()'s initWithImage:ocidNsImage

####最初のページに挿入する
ocidPdfActivDoc's insertPage:ocidPdfPage atIndex:0

####ファイルを保存する
set boolResponse to ocidPdfActivDoc's writeToURL:ocidSaveFilePathURL

set ocidNsImage to ""
set ocidPdfPage to ""
set ocidPdfActivDoc to ""

|

[NSimage]イメージ変換

少し修正した

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#error number -128
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "CoreImage"
use scripting additions


property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL

set aliasDefaultLocation to path to desktop folder from user domain

set listChooseFiles to (choose file with prompt "ファイルを選んでください" default location aliasDefaultLocation of type {"public.image"} with invisibles and multiple selections allowed without showing package contents) as list



repeat with objFile in listChooseFiles

set theFilePath to POSIX path of objFile
-->text
set ocidFilePath to (refNSString's stringWithString:theFilePath)
-->(*__NSCFString*)
set ocidFullPathURL to (refMe's NSURL's fileURLWithPath:ocidFilePath)
-->(*NSURL*)
#####拡張子を取って
set ocidBaseFilePathURL to ocidFullPathURL's URLByDeletingPathExtension()
-->(*NSURL*)
######新しい拡張子を加える
set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:"jpeg")
-->(*NSURL*)
(*
set ocidFileName to ocidFullPathURL's lastPathComponent
-->(*NSPathStore2*)ファイル名
set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
-->(*NSPathStore2*)ファイル名から拡張子を取ったいわゆるベースファイル名
set ocidFileExtension to ocidFilePath's pathExtension
-->(*NSPathStore2*)拡張子
set ocidContainDirPath to ocidFilePath's stringByDeletingLastPathComponent
-->(*NSPathStore2*)元ファイルのあるディレクトリ
set ocidSaveFileName to (ocidPrefixName's stringByAppendingString:".jpeg")
-->(*__NSCFString*)ベースファイル名に拡張子を追加して書き出しファイル名
set ocidSaveFilePath to (ocidContainDirPath's stringByAppendingPathComponent:ocidSaveFileName)
-->(*NSPathStore2*)コンテナディレクトリにファイル名を足して保存先
####ファイルパスのテキスト
set strSaveFilePath to ocidSaveFilePath as text
-->text ファイルパスをテキストで確定させて
set ocidSaveFilePath to (refMe's NSURL's fileURLWithPath:strSaveFilePath)
*)
-->(*NSURL*) NSURLを作り直し
###イメージデータ展開
set ocidImageRep to (refMe's NSBitmapImageRep's imageRepWithContentsOfFile:theFilePath)
####NSImageColorSyncProfileData
set ocidColorSpace to refMe's NSColorSpace's displayP3ColorSpace()
set ocidColorSpaceData to ocidColorSpace's colorSyncProfile()
####NSImageEXIFData
set ocidEXIFData to (ocidImageRep's valueForProperty:(refMe's NSImageEXIFData))
####NSImageFallbackBackgroundColor
set ocidBackGroundColor to (refMe's NSColor's colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:1.0)
####propertiesデータレコード整形
set ocidImageProperties to {NSImageCompressionFactor:0.0, NSImageProgressive:0, NSImageFallbackBackgroundColor:ocidBackGroundColor, NSImageEXIFData:ocidEXIFData, NSImageColorSyncProfileData:ocidColorSpaceData} as record
(*
NSImageEXIFData
NSImageProgressive
NSImageColorSyncProfileData
NSImageCompressionFactor
NSImageFallbackBackgroundColor

NSImageGamma
NSImageInterlaced

NSImageFrameCount
NSImageCurrentFrameDuration
NSImageCompressionMethod
NSImageDitherTransparency
NSImageLoopCount
NSImageCurrentFrame
NSImageRGBColorTable
*)
#####JPEGデータに変換
set ocidSaveData to (ocidImageRep's representationUsingType:(refMe's NSBitmapImageFileTypeJPEG) |properties|:ocidImageProperties)
(*
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeJPEG2000
*)
tell ocidImageRep
log bitsPerSample()
#####
log pixelsHigh()
log pixelsWide()
#####
log pixelsHigh()
log pixelsWide()
#####
log bitsPerPixel()
log bytesPerPlane()
log bitmapFormat()
log samplesPerPixel()
log hasAlpha()
log isOpaque()
log isPlanar()
log layoutDirection()
log colorSpaceName()
end tell
####ファイル書き出し
(*
set boolWroteToFileDone to (ocidSaveData's writeToFile:strSaveFilePath atomically:true)
log boolWroteToFileDone as boolean
*)
(*
set ocidWroteToFileDone to ocidSaveData's writeToURL:ocidSaveFilePath options:0
*)
(*
set ocidWroteToFileDone to (ocidSaveData's writeToFile:ocidSaveFilePath options:0 |error|:(reference))
log item 1 of ocidWroteToFileDone
log item 2 of ocidWroteToFileDone
*)
set ocidWroteToFileDone to (ocidSaveData's writeToURL:ocidSaveFilePathURL options:0 |error|:(reference))
log item 1 of ocidWroteToFileDone
log item 2 of ocidWroteToFileDone
(*
options
NSDataWritingAtomic:0
NSDataWritingWithoutOverwriting:1
NSDataWritingFileProtectionNone:0x10000000
NSDataWritingFileProtectionComplete:0x20000000
NSDataWritingFileProtectionCompleteUnlessOpen:0x30000000
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication:0x40000000
NSDataWritingFileProtectionMask:0xf0000000
*)
###releaseするとクラッシュするんだよねぇ
##ocidSaveData's release()
##ocidImageRep'S release()
set ocidSaveData to ""
set ocidImageRep to ""
end repeat

|

[NSimage]イメージ変換

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#error number -128
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "CoreImage"
use scripting additions


property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL

set aliasDefaultLocation to path to desktop folder from user domain

set listChooseFiles to (choose file with prompt "ファイルを選んでください" default location aliasDefaultLocation of type {"public.image"} with invisibles and multiple selections allowed without showing package contents) as list



repeat with objFile in listChooseFiles

set theFilePath to POSIX path of objFile
-->text
set ocidFilePath to (refNSString's stringWithString:theFilePath)
-->(*__NSCFString*)
set ocidFullPathURL to (refMe's NSURL's fileURLWithPath:ocidFilePath)
-->(*NSURL*)
set ocidFileName to ocidFullPathURL's lastPathComponent
-->(*NSPathStore2*)ファイル名
set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
-->(*NSPathStore2*)ファイル名から拡張子を取ったいわゆるベースファイル名
set ocidFileExtension to ocidFilePath's pathExtension
-->(*NSPathStore2*)拡張子
set ocidContainDirPath to ocidFilePath's stringByDeletingLastPathComponent
-->(*NSPathStore2*)元ファイルのあるディレクトリ
set ocidSaveFileName to (ocidPrefixName's stringByAppendingString:".jpeg")
-->(*__NSCFString*)ベースファイル名に拡張子を追加して書き出しファイル名
set ocidSaveFilePath to (ocidContainDirPath's stringByAppendingPathComponent:ocidSaveFileName)
-->(*NSPathStore2*)コンテナディレクトリにファイル名を足して保存先
####ファイルパスのテキスト
set strSaveFilePath to ocidSaveFilePath as text
-->text ファイルパスをテキストで確定させて
set ocidSaveFilePath to (refMe's NSURL's fileURLWithPath:strSaveFilePath)
-->(*NSURL*) NSURLを作り直し
###イメージデータ展開
set ocidImageRep to (refMe's NSBitmapImageRep's imageRepWithContentsOfFile:theFilePath)
####NSImageColorSyncProfileData
set ocidColorSpace to refMe's NSColorSpace's displayP3ColorSpace()
set ocidColorSpaceData to ocidColorSpace's colorSyncProfile()
####NSImageEXIFData
set ocidEXIFData to (ocidImageRep's valueForProperty:(refMe's NSImageEXIFData))
####NSImageFallbackBackgroundColor
set ocidBackGroundColor to (refMe's NSColor's colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:1.0)
####propertiesデータレコード整形
set ocidImageProperties to {NSImageCompressionFactor:0.0, NSImageProgressive:0, NSImageFallbackBackgroundColor:ocidBackGroundColor, NSImageEXIFData:ocidEXIFData, NSImageColorSyncProfileData:ocidColorSpaceData} as record
(*
NSImageEXIFData
NSImageProgressive
NSImageColorSyncProfileData
NSImageCompressionFactor
NSImageFallbackBackgroundColor

NSImageGamma
NSImageInterlaced

NSImageFrameCount
NSImageCurrentFrameDuration
NSImageCompressionMethod
NSImageDitherTransparency
NSImageLoopCount
NSImageCurrentFrame
NSImageRGBColorTable
*)
#####JPEGデータに変換
set ocidSaveData to (ocidImageRep's representationUsingType:(refMe's NSBitmapImageFileTypeJPEG) |properties|:ocidImageProperties)
(*
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeJPEG2000
*)
tell ocidImageRep
log bitsPerSample()
#####
log pixelsHigh()
log pixelsWide()
#####
log pixelsHigh()
log pixelsWide()
#####
log bitsPerPixel()
log bytesPerPlane()
log bitmapFormat()
log samplesPerPixel()
log hasAlpha()
log isOpaque()
log isPlanar()
log layoutDirection()
log colorSpaceName()
end tell
####ファイル書き出し
(*
set boolWroteToFileDone to (ocidSaveData's writeToFile:strSaveFilePath atomically:true)
log boolWroteToFileDone as boolean
*)
(*
set ocidWroteToFileDone to ocidSaveData's writeToURL:ocidSaveFilePath options:0
*)
(*
set ocidWroteToFileDone to (ocidSaveData's writeToFile:ocidSaveFilePath options:0 |error|:(reference))
log item 1 of ocidWroteToFileDone
log item 2 of ocidWroteToFileDone
*)
set ocidWroteToFileDone to (ocidSaveData's writeToURL:ocidSaveFilePath options:0 |error|:(reference))
log item 1 of ocidWroteToFileDone
log item 2 of ocidWroteToFileDone
(*
options
NSDataWritingAtomic:0
NSDataWritingWithoutOverwriting:1
NSDataWritingFileProtectionNone:0x10000000
NSDataWritingFileProtectionComplete:0x20000000
NSDataWritingFileProtectionCompleteUnlessOpen:0x30000000
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication:0x40000000
NSDataWritingFileProtectionMask:0xf0000000
*)
end repeat

|

[NSBitmapImageRep]画像の解像度変更(resolution)

pngファイル144ppi -->スクリーンキャプチャーの解像度

pngファイル72ppiに変更します
解像度の変更のみですので、画像のpixelサイズは元画像のままです


#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSMutableString : a reference to refMe's NSMutableString
property refNSURL : a reference to refMe's NSURL
property refNSImage : a reference to refMe's NSImage



####ダイアログで使うデフォルトロケーション
tell application "Finder"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell

####UTIリスト PDFのみ
set listUTI to {"public.png"}

####ダイアログを出す
set aliasFilePath to (choose file with prompt "PNGイメージファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

set strFilePath to POSIX path of aliasFilePath


##Make NSString
set ocidNSString to refNSString's stringWithString:strFilePath
log ocidNSString as text
log ocidNSString's className() as text
####NSimageに格納
set ocidImageData to refNSImage's alloc()'s initWithContentsOfFile:strFilePath
log ocidImageData
log className() of ocidImageData as text
###サイズ取得PT
set ocidImageSize to ocidImageData's |size|()
log ocidImageSize
log class of ocidImageSize as text
log "#####"
###representations取得
set ocidImageRepArray to ocidImageData's representations()
log ocidImageRepArray
log className() of ocidImageRepArray as text
###NSBitmapImageRep取得
set ocidImageRep to (ocidImageRepArray's objectAtIndex:0)
log ocidImageRep
log className() of ocidImageRep as text
####ピクセル単位での幅
set numpixelsWidth to ocidImageRep's pixelsWide()
log numpixelsWidth
log class of numpixelsWidth as text
####ピクセル単位での高さ
set numpixelsHeight to ocidImageRep's pixelsHigh()
log numpixelsHeight
log class of numpixelsHeight as text
####ポイント単位でのサイズ
set ocidImageRepSize to ocidImageRep's |size|()
log ocidImageRepSize
log class of ocidImageRepSize as text
####ポイント単位での幅と高さ
set numPointWidth to width of ocidImageRepSize
set numPointHeight to height of ocidImageRepSize
log numPointWidth
log numPointHeight
####イメージの解像度
set numCurrentDPI to ((72 * numpixelsWidth) / numPointWidth) as integer
log numCurrentDPI
####変更後のポイントサイズを求める
set numNewImageWidth to ((72.0 * numpixelsWidth) / 72)
set numNewImageHeight to ((72.0 * numpixelsHeight) / 72)
set recordNewImageSize to {width:numNewImageWidth, height:numNewImageHeight} as record
log recordNewImageSize
####ImageRepをポイントサイズに変更
ocidImageRep's setSize:recordNewImageSize
###確認用
set ocidImageRepSize to ocidImageRep's |size|()
log ocidImageRepSize
log class of ocidImageRepSize as text
###PNGで保存する
set ocidSaveImageType to refMe's NSBitmapImageFileTypePNG
###インターレースとアルファは保持
set ocidNewImageData to ocidImageRep's representationUsingType:ocidSaveImageType |properties|:{NSImageInterlaced:true, NSImageDitherTransparency:true}
###上書き保存
ocidNewImageData's writeToFile:strFilePath atomically:false

set ocidImageRep to ""
set ocidNewImageData to ""

#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
tell application "Script Editor"
tell application "System Events"
tell process "Script Editor"
tell window 1
tell splitter group 1
tell splitter group 1
tell group 1
tell checkbox "返された値"
set boolValue to value as boolean
end tell
if boolValue is false then
click checkbox "返された値"
end if
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end if
end repeat

end doLogView
#########################

|

[NSimages]画像の解像度ppiを求める

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSMutableString : a reference to refMe's NSMutableString
property refNSURL : a reference to refMe's NSURL

property refNSNotFound : a reference to 9.22337203685477E+18 + 5807
property refNSImage : a reference to refMe's NSImage
set objFileManager to refMe's NSFileManager's defaultManager()

set strFilePath to "/System/Library/Desktop Pictures/Big Sur Graphic.heic"

##Make NSString
set ocidNSString to refNSString's stringWithString:strFilePath
log ocidNSString as text
log ocidNSString's className() as text
####NSimageに格納
set ocidImageData to refNSImage's alloc()'s initWithContentsOfFile:strFilePath
log ocidImageData
log className() of ocidImageData as text
###サイズ取得PT
set ocidImageSize to ocidImageData's |size|()
log ocidImageSize
log class of ocidImageSize as text
log "#####"
###representations取得
set ocidImageRepArray to ocidImageData's representations()
log ocidImageRepArray
log className() of ocidImageRepArray as text
###NSBitmapImageRep取得
set ocidImageRep to (ocidImageRepArray's objectAtIndex:0)
log ocidImageRep
log className() of ocidImageRep as text
####ピクセル単位での幅
set numpixelsWidth to ocidImageRep's pixelsWide()
log numpixelsWidth
log class of numpixelsWidth as text
####ピクセル単位での高さ
set numpixelsHeight to ocidImageRep's pixelsHigh()
log numpixelsHeight
log class of numpixelsHeight as text
####ポイント単位でのサイズ
set ocidImageRepSize to ocidImageRep's |size|()
log ocidImageRepSize
log class of ocidImageRepSize as text
####ポイント単位での幅と高さ
set numPointWidth to width of ocidImageRepSize
set numPointHeight to height of ocidImageRepSize
log numPointWidth
log numPointHeight
####イメージの解像度
set numCurrentDPI to ((72 * numpixelsWidth) / numPointWidth) as integer
log numCurrentDPI





#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
tell application "Script Editor"
tell application "System Events"
tell process "Script Editor"
tell window 1
tell splitter group 1
tell splitter group 1
tell group 1
tell checkbox "返された値"
set boolValue to value as boolean
end tell
if boolValue is false then
click checkbox "返された値"
end if
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end if
end repeat

end doLogView
#########################

|

[NSBitmapImageRep]画像のサイズ変更(CROP)

元画像
左用と右用のファイルに複製
順番に開いて変更後のCROPサイズでNSBitmapImageRepを作成
元画像をNSBitmapImageRepに場所指定してNSCompositeSourceOverする
(小さいサイズに大きいサイズを座標で上から置くのではみ出た部分は削除される)
-->この方法が正しいか?は疑問だがQRコード作った時の使い回し
出来上がったCROP画像データをファイルに『上書き』で『書き出す』



#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions
use framework "UniformTypeIdentifiers"

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSURL : a reference to objMe's NSURL

property objNSArray : a reference to objMe's NSArray
property objNSMutableArray : a reference to objMe's NSMutableArray
property objUTType : a reference to objMe's UTType

property objNSDictionary : a reference to NSDictionary

property objNSImage : a reference to objMe's NSImage
property objNSBitmapImageRep : a reference to objMe's NSBitmapImageRep
property objNSGraphicsContext : a reference to objMe's NSGraphicsContext

set objFileManager to objMe's NSFileManager's defaultManager()
set ocidNSURLIsRegularFileKey to objMe's NSURLIsRegularFileKey

############################################
###設定項目##左右ページ 右から左ならtrue 左から右ならfalse
############################################
set boolRtoL to true as boolean

############################################
######ログ表示
doLogView()

tell application "Finder"
##set aliasDefaultLocation to container of (path to me) as alias
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell

try
set aliasResponse to (choose folder "画像が入っているフォルダを選んでください" with prompt "フォルダを選択してください" default location aliasDefaultLocation without multiple selections allowed, invisibles and showing package contents)
on error
log "エラーしました"
return
end try


###パス
set strDirPath to POSIX path of aliasResponse as text
###NSStringテキスト
set ocidDirPath to (objNSString's stringWithString:strDirPath)
#####NSURL NSStringURL
set ocidDirUrlPath to (objNSURL's fileURLWithPath:ocidDirPath)
###不可視ファイル以外のファイルを取得
set ocidContentsArray to objFileManager's contentsOfDirectoryAtURL:ocidDirUrlPath includingPropertiesForKeys:{ocidNSURLIsRegularFileKey} options:(objMe's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
####可変リストに変更
set ocidSortedArrayM to objNSMutableArray's arrayWithArray:ocidContentsArray
#####UNIXパス形式
set ocidSortedArrayM to ocidSortedArrayM's valueForKeyPath:"path"
###ローカライズ順でソート
set ocidSortedArrayM to (ocidSortedArrayM's sortedArrayUsingSelector:"localizedCompare:")
###出来上がりファイル番号のカウント
set numFileCntNo to 0 as number
###ファイルの数だけ繰り返し
repeat with objSortedArrayM in ocidSortedArrayM
####拡張子名
set strExtension to objSortedArrayM's pathExtension as text
log
if strExtension is "" then
log "対象ファイル外なのでそのままにする"
else
####拡張子からUTI取得
set ocidUTType to (objUTType's typeWithFilenameExtension:strExtension)
set strUTI to ocidUTType's identifier as text
####UTIからMIME取得
set ocidFileMimeType to ocidUTType's preferredMIMEType()
set strFileMimeType to ocidFileMimeType as text
####ファイル名
set ocidFileName to objSortedArrayM's lastPathComponent
set strFileName to ocidFileName as text
####拡張子を除いたファイル名
set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
#####ファイル名に加える『接頭名』を指定
####ファイル名用番号(2桁ゼロサプレス)
if boolRtoL is true then
set numFileCntNo to (numFileCntNo + 1) as number
set strSplitFileNo to "000" & numFileCntNo as text
set strSplitFileNo to text -3 through -1 of strSplitFileNo as text
set strRpageNameHeader to (strSplitFileNo & "_R_") as text
set strRpageName to (strRpageNameHeader & strFileName) as text
set strRsaveFilePath to (strDirPath & strRpageName) as text
set ocidDistFilePathR to (objNSURL's fileURLWithPath:strRsaveFilePath)

set numFileCntNo to (numFileCntNo + 1) as number
set strSplitFileNo to "000" & numFileCntNo as text
set strSplitFileNo to text -3 through -1 of strSplitFileNo as text
set strLpageNameHeader to (strSplitFileNo & "_L_") as text
set strLpageName to (strLpageNameHeader & strFileName) as text
set strLsaveFilePath to (strDirPath & strLpageName) as text
set ocidDistFilePathL to (objNSURL's fileURLWithPath:strLsaveFilePath)
else
set numFileCntNo to (numFileCntNo + 1) as number
set strSplitFileNo to "000" & numFileCntNo as text
set strSplitFileNo to text -3 through -1 of strSplitFileNo as text
set strLpageNameHeader to (strSplitFileNo & "_L_") as text
set strLpageName to (strLpageNameHeader & strFileName) as text
set strLsaveFilePath to (strDirPath & strLpageName) as text
set ocidDistFilePathL to (objNSURL's fileURLWithPath:strLsaveFilePath)


set numFileCntNo to (numFileCntNo + 1) as number
set strSplitFileNo to "000" & numFileCntNo as text
set strSplitFileNo to text -3 through -1 of strSplitFileNo as text
set strRpageNameHeader to (strSplitFileNo & "_R_") as text
set strRpageName to (strRpageNameHeader & strFileName) as text
set strRsaveFilePath to (strDirPath & strRpageName) as text
set ocidDistFilePathR to (objNSURL's fileURLWithPath:strRsaveFilePath)

end if

####MIMEの照合
if strFileMimeType is "image/jpeg" then
log "リストに項目がある"
set boolFileCopyDoneR to (objFileManager's copyItemAtPath:objSortedArrayM toPath:ocidDistFilePathR |error|:(boolean))
set boolFileCopyDoneL to (objFileManager's copyItemAtPath:objSortedArrayM toPath:ocidDistFilePathL |error|:(boolean))

if boolFileCopyDoneR is true then
log "Rファイルはコピーされました"
if boolFileCopyDoneL is true then
log "Lファイルはコピーされました"
#####NSURL NSStringURL
set ocidOrignalFileUrlPath to (objNSURL's fileURLWithPath:objSortedArrayM)
log "対象ファイル外なのでゴミ箱へ"
set boolGoToTrash to (objFileManager's trashItemAtURL:ocidOrignalFileUrlPath resultingItemURL:(missing value) |error|:(""))
if boolGoToTrash is true then
log "オリジナルファイルはゴミ箱へ入れました"
else
log "ゴミ箱へ入れるのを失敗しました"
end if
else if boolFileCopyDoneL is false then
log "Lファイルコピーは失敗しました"
end if
else if boolFileCopyDoneR is false then
log "Rファイルコピーは失敗しました"
end if

else if strFileMimeType is "image/png" then
log "リストに項目がある"
set boolFileCopyDoneR to (objFileManager's copyItemAtPath:objSortedArrayM toPath:ocidDistFilePathR |error|:(boolean))
set boolFileCopyDoneL to (objFileManager's copyItemAtPath:objSortedArrayM toPath:ocidDistFilePathL |error|:(boolean))
###左と右の分岐
if boolFileCopyDoneR is true then
log "Rファイルはコピーされました"
if boolFileCopyDoneL is true then
log "Lファイルはコピーされました"
#####NSURL NSStringURL
set ocidOrignalFileUrlPath to (objNSURL's fileURLWithPath:objSortedArrayM)
log "対象ファイル外なのでゴミ箱へ"
set boolGoToTrash to (objFileManager's trashItemAtURL:ocidOrignalFileUrlPath resultingItemURL:(missing value) |error|:(""))
if boolGoToTrash is true then
log "オリジナルファイルはゴミ箱へ入れました"
else
log "ゴミ箱へ入れるのを失敗しました"
end if
else if boolFileCopyDoneL is false then
log "Lファイルコピーは失敗しました"
end if
else if boolFileCopyDoneR is false then
log "Rファイルコピーは失敗しました"
end if

else
set numFileCntNo to (numFileCntNo - 2) as number
#####NSURL NSStringURL
set ocidOrignalFileUrlPath to (objNSURL's fileURLWithPath:objSortedArrayM)
log "対象ファイル外なのでゴミ箱へ"
set boolGoToTrash to (objFileManager's trashItemAtURL:ocidOrignalFileUrlPath resultingItemURL:(missing value) |error|:(""))
if boolGoToTrash is true then
log "オリジナルファイルはゴミ箱へ入れました"
else
log "ゴミ箱へ入れるのを失敗しました"
end if
end if

end if
end repeat

#############################################
(*
ここで、ファイルの複製(左用と右用)が出来たので
再度ファイルリストを取り直す
*)

###不可視ファイル以外のファイルを取得
set ocidContentsArrayNEW to objFileManager's contentsOfDirectoryAtURL:ocidDirUrlPath includingPropertiesForKeys:{ocidNSURLIsRegularFileKey} options:(objMe's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
####可変リストに変更
set ocidContentsArrayNewM to objNSMutableArray's arrayWithArray:ocidContentsArrayNEW
#####UNIXパス形式
set ocidContentsArrayNewM to ocidContentsArrayNewM's valueForKeyPath:"path"
###ローカライズ順でソート
set ocidSortedArrayNewM to (ocidContentsArrayNewM's sortedArrayUsingSelector:"localizedCompare:")

###ファイルの数だけ繰り返し
repeat with objSortedArrayNewM in ocidSortedArrayNewM
###パスで来るのでテキストに
set strSortedArrayNewMObj to objSortedArrayNewM as text
###パスをエイリアスに
set aliasContentsFilePath to POSIX file strSortedArrayNewMObj as alias
###########################
tell application "System Events"
set objKind to kind of aliasContentsFilePath
if objKind is "PNGイメージ" then
set boolKindChk to true as boolean
####PNG用の圧縮プロパティ
else if objKind is "JPEGイメージ" then
set boolKindChk to true as boolean
####JPEG用の圧縮プロパティ
else
set boolKindChk to false as boolean
end if
end tell

####NSStリングに
set ocidSortedFilePath to (objNSString's stringWithString:strSortedArrayNewMObj)
####ファイル名
set ocidFileName to ocidSortedFilePath's lastPathComponent
set strFileName to ocidFileName as text
####拡張子を除いたパス
set ocidSortedFileNamePath to ocidSortedFilePath's stringByDeletingPathExtension()
###拡張子
set strFileExtension to ocidSortedFilePath's pathExtension() as text
###保存パスここでは上書きなので同じにする
set ocidSaveFilePath to ocidSortedFilePath
####ファイルを読み込み NSBitmapImageRep
set ocidBitmapImageRepObj to (objNSBitmapImageRep's imageRepWithContentsOfFile:objSortedArrayNewM)
set numImageRepHight to ocidBitmapImageRepObj's pixelsHigh() as integer
set numImageRepWidth to ocidBitmapImageRepObj's pixelsWide() as integer
set numImageRepBytePerPlane to (numImageRepHight * numImageRepWidth) as integer
log numImageRepHight
log numImageRepWidth
log numImageRepBytePerPlane
####ページの半分の幅
set numImageRepWidthHarf to numImageRepWidth / 2 as integer
log numImageRepWidthHarf
#######ファイルを読み込み NSImage
set ocidNSImageFileObj to (objNSImage's alloc()'s initWithContentsOfFile:objSortedArrayNewM)
set recordSize to (ocidNSImageFileObj's |size|()) as record
set numNSImageHeight to height of recordSize as integer
set numNSImageWidth to width of recordSize as integer
set numNSImageBytePerPlane to (numNSImageHeight * numNSImageWidth) as integer
log numNSImageHeight
log numNSImageWidth
log numNSImageBytePerPlane
####ページの半分の幅
set numNSImageWidthHarf to numNSImageWidth / 2 as integer
log numNSImageWidthHarf
#### 解像度を求める
set numResolution to (((numImageRepBytePerPlane / numNSImageBytePerPlane) ^ 0.5) * 72) as integer
####NSImageのサイズで『半分の』サイズのNSBitmapImageRepを作成する
set ocidNewImageRep to (objNSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:numNSImageWidthHarf pixelsHigh:numNSImageHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(objMe's NSCalibratedRGBColorSpace) bitmapFormat:(objMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
####処理開始
objNSGraphicsContext's saveGraphicsState()
#####半分サイズのイメージをgraphicsContextに変換
(objNSGraphicsContext's setCurrentContext:(objNSGraphicsContext's graphicsContextWithBitmapImageRep:ocidNewImageRep))
objMe's NSColor's grayColor()'s |set|()
#### 座標と幅高さを指定
objMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numNSImageWidthHarf, height:numNSImageHeight}})

if boolRtoL is true then
#####右から左へのパターン
if strFileName contains "_R_" then
###新規画像の座標00に開いた画像の座標00を描画する
(ocidBitmapImageRepObj's drawInRect:{origin:{x:0, y:0}, |size|:{width:numNSImageWidthHarf, height:numNSImageHeight}} fromRect:{origin:{x:numNSImageWidthHarf, y:0}, |size|:{width:numNSImageWidthHarf, height:numNSImageHeight}} operation:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value))
else if strFileName contains "_L_" then
#####新規画像の座標00に開いた画像の座標幅を半分にした部分でを描画する
(ocidBitmapImageRepObj's drawInRect:{origin:{x:0, y:0}, |size|:{width:numImageRepWidthHarf, height:numImageRepHight}} fromRect:{origin:{x:0, y:0}, |size|:{width:numImageRepWidthHarf, height:numImageRepHight}} operation:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value))
else
return false
end if
else if boolRtoL is false then
#####右から左へのパターン
if strFileName contains "_L_" then
###新規画像の座標00に開いた画像の座標00を描画する
(ocidBitmapImageRepObj's drawInRect:{origin:{x:0, y:0}, |size|:{width:numImageRepWidthHarf, height:numImageRepHight}} fromRect:{origin:{x:0, y:0}, |size|:{width:numImageRepWidthHarf, height:numImageRepHight}} operation:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value))
else if strFileName contains "_R_" then
#####新規画像の座標00に開いた画像の座標幅を半分にした部分でを描画する
(ocidBitmapImageRepObj's drawInRect:{origin:{x:0, y:0}, |size|:{width:numNSImageWidthHarf, height:numNSImageHeight}} fromRect:{origin:{x:numNSImageWidthHarf, y:0}, |size|:{width:numNSImageWidthHarf, height:numNSImageHeight}} operation:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value))
else
return false
end if
end if
####処理終了
objNSGraphicsContext's restoreGraphicsState()

###########################
tell application "System Events"
set objKind to kind of aliasContentsFilePath
if objKind is "PNGイメージ" then
set boolKindChk to true as boolean
####PNG用の圧縮プロパティで出力用フォーマットに変換
set ocidInlineImageData to (ocidNewImageRep's representationUsingType:(objMe's NSPNGFileType) |properties|:{NSImageInterlaced:true})
else if objKind is "JPEGイメージ" then
set boolKindChk to true as boolean
####JPEG用の圧縮プロパティで出力用フォーマットに変換
set ocidInlineImageData to (ocidNewImageRep's representationUsingType:(objMe's NSJPEGFileType) |properties|:{NSImageCompressionFactor:0.9, NSImageProgressive:false})
else
set boolKindChk to false as boolean
return false
end if
end tell
(ocidInlineImageData's writeToFile:ocidSaveFilePath atomically:true)

set ocidInlineImageData to ""
set ocidBitmapImageRepObj to ""
end repeat



#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

[Resolution]解像度を求める

たぶん、もっとスマートな方法があるに違いない

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSImage : a reference to NSImage
property objNSBitmapImageRep : a reference to NSBitmapImageRep

######ログ表示
doLogView()
###動作確認している分だけ
set listUTI to {"public.jpeg", "public.png", "org.webmproject.webp", "public.heic", "public.bmp"}
###ダイアログのデフォルトロケーション
tell application "Finder"
## set aliasDefaultLocation to container of (path to me) as alias
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell

###ダイアログ
set aliasFile to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

###エイリアスをUNIXパスに
set strFilePath to POSIX path of aliasFile as text

####NSBitmapImageRepの処理
set ocidBitmapImageRepObj to (objNSBitmapImageRep's imageRepWithContentsOfFile:strFilePath)
###
set numImageRepHight to ocidBitmapImageRepObj's pixelsHigh() as integer
###
set numImageRepWide to ocidBitmapImageRepObj's pixelsWide() as integer
####ピクセル数
set numImageRepBytePerPlane to (numImageRepHight * numImageRepWide) as integer

log numImageRepHight
log numImageRepWide
log numImageRepBytePerPlane
#####NSImageの処理
set ocidNSImageFileObj to (objNSImage's alloc()'s initWithContentsOfFile:strFilePath)
set recordSize to (ocidNSImageFileObj's |size|()) as record
###
set numNSImageHeight to height of recordSize as integer
###
set numNSImageWidth to width of recordSize as integer
####ピクセル数
set numNSImageBytePerPlane to (numNSImageHeight * numNSImageWidth) as integer
log numNSImageHeight
log numNSImageWidth
log numNSImageBytePerPlane
####解像度を求める
set numResolution to (((numImageRepBytePerPlane / numNSImageBytePerPlane) ^ 0.5) * 72) as integer


log numResolution





#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript Plist System Events AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom