NSImage

[NSImageRep] 画像の解像度(ピクセル密度)を取得する


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#
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
014set strFilePath to "/Library/User Pictures/Animals/Eagle.heic" as text
015set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
016set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
017set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
018
019# doGetImageSize(ファイルパスのURL)
020# {true, {{width:幅mm height:mm}, {width:幅px, height:縦px},解像度}
021set listResponse to doGetImageSize(ocidFilePathURL)
022if (item 1 of listResponse) = (true) then
023  log "正常処理 : "
024  set listImageSize to (item 2 of listResponse)
025  set numWmm to (width of (item 1 of listImageSize)) as real
026  set numHmm to (height of (item 1 of listImageSize)) as real
027  set numWpx to (width of (item 2 of listImageSize)) as real
028  set numHpx to (height of (item 2 of listImageSize)) as real
029  set numResolution to (item 3 of listImageSize) as real
030  log listResponse
031else if (item 1 of listResponse) = (false) then
032  log (item 2 of listResponse) as text
033  return "エラーしました"
034end if
035
036##############################
037# 画像のサイズと解像度
038#戻り値は
039# {true, {{width:幅mm height:mm}, {width:幅px, height:縦px},解像度}
040##############################
041to doGetImageSize(argFilePathURL)
042  # NSData
043  set ocidOption to (current application's NSDataReadingMappedIfSafe)
044  set listResponse to current application's NSData's dataWithContentsOfURL:(argFilePathURL) options:(ocidOption) |error| :(reference)
045  if (item 2 of listResponse) is (missing value) then
046    set ocidReadData to (item 1 of listResponse)
047    log "dataWithContentsOfURL 正常終了"
048  else
049    log (item 2 of listResponse)'s code() as text
050    set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
051    set listReturnValue to {false, strErrorMes} as list
052    return listReturnValue
053  end if
054  # NSImage
055  set ocidImageData to current application's NSImage's alloc()'s initWithData:(ocidReadData)
056  if ocidImageData = (missing value) then
057    set listReturnValue to {false, "NSImageの内容が空です"} as list
058    return listReturnValue
059  end if
060  set ocidImageSizePt to ocidImageData's |size|()
061  #ポイントサイズ取得
062  set numWpt to ocidImageSizePt's width()
063  set numHpt to ocidImageSizePt's height()
064  #DecimalNumberに
065  set ocidDecWpt to current application's NSDecimalNumber's alloc()'s initWithString:(numWpt as text)
066  set ocidDecHpt to current application's NSDecimalNumber's alloc()'s initWithString:(numHpt as text)
067  #計算に必要な値
068  set ocidDecPt to current application's NSDecimalNumber's alloc()'s initWithString:("72")
069  set ocidDecIn to current application's NSDecimalNumber's alloc()'s initWithString:("25.4")
070  #幅pt÷72
071  set ocidFloatWpt to (ocidDecWpt's decimalNumberByDividingBy:(ocidDecPt))
072  #縦pt÷72
073  set ocidFloatHpt to (ocidDecHpt's decimalNumberByDividingBy:(ocidDecPt))
074  #(幅pt÷72)x25.4=幅MM
075  set ocidMMWpt to (ocidFloatWpt's decimalNumberByMultiplyingBy:(ocidDecIn))
076  #(縦pt÷72)x25.4=縦MM
077  set ocidMMHpt to (ocidFloatHpt's decimalNumberByMultiplyingBy:(ocidDecIn))
078  #小数点以下2位で四捨五入
079  set appFormatter to current application's NSNumberFormatter's alloc()'s init()
080  appFormatter's setRoundingMode:(current application's NSNumberFormatterRoundUp)
081  appFormatter's setNumberStyle:(current application's NSNumberFormatterDecimalStyle)
082  appFormatter's setUsesGroupingSeparator:(false)
083  appFormatter's setMaximumFractionDigits:(2)
084  #幅MM
085  set ocidWmm to appFormatter's stringFromNumber:(ocidMMWpt)
086  #縦MM
087  set ocidHmm to appFormatter's stringFromNumber:(ocidMMHpt)
088  # NSImageRepに変換
089  set ocidImageRepArray to ocidImageData's representations()
090  #ImageRepの数を数えて
091  set numCntImageRep to ocidImageRepArray's |count|()
092  if numCntImageRep = 0 then
093    set listReturnValue to {false, "NSImageRepの内容が空です"} as list
094    return listReturnValue
095  else if numCntImageRep > 1 then
096    log "マルチページデータです:最初のページのサイズを取得します"
097    set ocidItemImageData to ocidImageRepArray's firstObject()
098  else if numCntImageRep = 1 then
099    set ocidItemImageData to ocidImageRepArray's firstObject()
100    #フレームがあるか?を確認します
101    set ocidFrameCnt to (ocidItemImageData's valueForProperty:(refMe's NSImageFrameCount))
102    if ocidFrameCnt = (missing value) then
103      log "通常の画像データです"
104    else if (ocidFrameCnt's integerValue()) > 0 then
105      log "GIF画像データです"
106    end if
107  end if
108  #ピクセルサイズ取得
109  set numWpx to ocidItemImageData's pixelsWide()
110  set numHpx to ocidItemImageData's pixelsHigh()
111  #解像度(ピクセル密度)
112  set ocidDecWpx to current application's NSDecimalNumber's alloc()'s initWithString:(numWpx as text)
113  set ocidResolutioW to (ocidDecWpx's decimalNumberByDividingBy:(ocidDecWpt))
114  set ocidResolutin to (ocidResolutioW's decimalNumberByMultiplyingBy:(ocidDecPt))
115  #解像度は桁揃えしておく
116  set ocidResolution to appFormatter's stringFromNumber:(ocidResolutin)
117  set ocidResolution to appFormatter's stringFromNumber:(ocidResolutin)
118  #戻り値用のリスト
119  # {true, {{width:幅mm height:mm}, {width:幅px, height:縦px},解像度}
120  set listReturnValue to {true, {{width:(ocidWmm as real), height:(ocidHmm as real)}, {width:numWpx, height:numHpx}, (ocidResolution as real)}} as list
121  #戻す
122  return listReturnValue
123  
124end doGetImageSize
AppleScriptで生成しました

|

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


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

#!/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

|

[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
#########################

|

[WKWebView]QRコードを表示する

webViewの基本構造はこちらを使用しています。
https://macscripter.net/viewtopic.php?pid=209146



#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#webViewベーススクリプト
#https://macscripter.net/viewtopic.php?pid=209146
#
# 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 "WebKit"
use scripting additions

property objMe : a reference to current application
property objNSURL : a reference to objMe's NSURL
property objNSString : a reference to objMe's NSString
set objFileManager to objMe's NSFileManager's defaultManager()

#####################################
set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns" as alias
set theResponse to "" as text
try
set objResponse to (display dialog "バーコードの内容を入力" with title "QRコードを作成します" default answer theResponse buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 20 without hidden answer)
on error
log "エラーしました"
return
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
end if
if "OK" is equal to (button returned of objResponse) then
set strText to (text returned of objResponse) as text
else
return "キャンセル"
end if
###フォルダのパス
###ピクチャーフォルダのパス
set aliasDirPath to (path to pictures folder from user domain) as alias
set strDirPath to POSIX path of aliasDirPath as text
####フォルダ名
set strFolderName to "QRcode" as text
set strDirPath to ("" & strDirPath & strFolderName & "") as text
###NSStringテキスト
set ocidDirPath to objNSString's stringWithString:strDirPath
###フォルダを作る
###途中のフォルダも作る-->true
set boolMakeNewFolder to (objFileManager's createDirectoryAtPath:ocidDirPath withIntermediateDirectories:true attributes:(missing value) |error|:(missing value))

####日付フォーマット
set prefDateFormat to "yyyyMMddHHmmss"
set ocidFormatter to objMe's NSDateFormatter's alloc()'s init()
ocidFormatter's setLocale:(objMe's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidFormatter's setDateFormat:(prefDateFormat as string)
set strDateAndTime to (ocidFormatter's stringFromDate:(current date)) as text
#####日付をファイル名にする
set strSaveFilePath to strDirPath & "/" & strDateAndTime & ".png"

#####################################
set strInputText to (strText) as text
####テキストをNSString
set ocidInputString to objNSString's stringWithString:strInputText
#####################################
##全角を半角に変換して
set ocidInputStringHalfwidth to (ocidInputString's stringByApplyingTransform:(objMe's NSStringTransformFullwidthToHalfwidth) |reverse|:false)
##制御文字取り除き
set ocidwhitespaceAndNewlineCharacterSet to objMe's NSCharacterSet's whitespaceAndNewlineCharacterSet
set ocidInputString to ocidInputStringHalfwidth's stringByTrimmingCharactersInSet:ocidwhitespaceAndNewlineCharacterSet
##スペース取り除き
set ocidSearchString to objNSString's stringWithString:" "
set ocidReplacementString to objNSString's stringWithString:""
set ocidTrimmingText to ocidInputString's stringByReplacingOccurrencesOfString:ocidSearchString withString:ocidReplacementString
##ハイフン取り除き
set ocidSearchString to objNSString's stringWithString:"-"
set ocidTrimmingText to ocidTrimmingText's stringByReplacingOccurrencesOfString:ocidSearchString withString:ocidReplacementString
#####################################
####テキストをUTF8
set ocidUtf8InputString to ocidTrimmingText's dataUsingEncoding:(objMe's NSUTF8StringEncoding)
####CIQRCodeGenerator初期化
set ocidQRcodeImage to objMe's CIFilter's filterWithName:"CIQRCodeGenerator"
ocidQRcodeImage's setDefaults()
###テキスト設定
ocidQRcodeImage's setValue:ocidUtf8InputString forKey:"inputMessage"
###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:"Q" forKey:"inputCorrectionLevel"
###QRコード本体のイメージ
set ocidCIImage to ocidQRcodeImage's outputImage()
-->ここで生成されるのはQRのセルが1x1pxの最小サイズ
###QRコードの縦横取得
set ocidCIImageDimension to ocidCIImage's extent()
set ocidCIImageWidth to (item 1 of item 2 of ocidCIImageDimension) as integer
set ocidCIImageHight to (item 2 of item 2 of ocidCIImageDimension) as integer
###最終的に出力したいpxサイズ
set numScaleMax to 580
###整数で拡大しないとアレなのでの値のニアなサイズになります
set numWidth to ((numScaleMax / ocidCIImageWidth) div 1) as integer
set numHight to ((numScaleMax / ocidCIImageHight) div 1) as integer
###↑サイズの拡大縮小する場合はここで値を調整すれば良い
####変換スケール作成-->拡大
set recordScalse to objMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:recordScalse
#######元のセルが1x1pxの最小サイズで出したいときはここで処理
##set ocidCIImageScaled to ocidCIImage
###イメージデータを展開
set ocidNSCIImageRep to objMe's NSCIImageRep's imageRepWithCIImage:ocidCIImageScaled
###出力用のイメージの初期化
set ocidNSImageScaled to objMe's NSImage's alloc()'s initWithSize:(ocidNSCIImageRep's |size|())
###イメージデータを合成
ocidNSImageScaled's addRepresentation:ocidNSCIImageRep
###出来上がったデータはOS_dispatch_data
set ocidOsDispatchData to ocidNSImageScaled's TIFFRepresentation()
####NSBitmapImageRep
set ocidNSBitmapImageRep to objMe's NSBitmapImageRep's imageRepWithData:ocidOsDispatchData
#####################################
###quiet zone用に画像をパディングする
set numPadWidth to ((ocidCIImageWidth * numWidth) + (numWidth * 6)) as integer
set numPadHight to ((ocidCIImageHight * numHight) + (numHight * 6)) as integer
###左右に4セル分づつ余白 quiet zoneを足す
####まずは元のQRコードのサイズに8セルサイズ分足したサイズの画像を作って
set ocidNSBitmapImagePadRep to (objMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:numPadWidth pixelsHigh:numPadHight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(objMe's NSCalibratedRGBColorSpace) bitmapFormat:(objMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
###初期化
objMe's NSGraphicsContext's saveGraphicsState()
###ビットマップイメージ
(objMe's NSGraphicsContext's setCurrentContext:(objMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:ocidNSBitmapImagePadRep))
###塗り色を『白』に指定して
objMe's NSColor's whiteColor()'s |set|()
###画像にする
objMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}})
###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
ocidNSBitmapImageRep's drawInRect:{origin:{x:(numWidth * 3), y:(numHight * 3)}, |size|:{width:numPadWidth, Hight:numPadHight}} fromRect:{origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}} operation:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
objMe's NSGraphicsContext's restoreGraphicsState()

#####################################
####JPEG用の圧縮プロパティ
##set ocidNSSingleEntryDictionary to objMe's NSDictionary's dictionaryWithObject:1 forKey:(objMe's NSImageCompressionFactor)
####PNG用の圧縮プロパティ
set ocidNSSingleEntryDictionary to objMe's NSDictionary's dictionaryWithObject:true forKey:(objMe's NSImageInterlaced)

#####出力イメージへ変換
set ocidNSInlineData to (ocidNSBitmapImagePadRep's representationUsingType:(objMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
(*
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeJPEG2000
*)
######インラインデータをファイルに書き出し
set boolMakeQrCode to (ocidNSInlineData's writeToFile:strSaveFilePath atomically:true)

set targetURL to ("file://" & strSaveFilePath & "") as text
#####################################
repeat 1 times
####NSMutableDictionaryの初期化
set ocidNSDictionaryM to objMe's NSMutableDictionary's dictionary()
####ウィンドのサイズ
set {numWidth, numHeight} to {600, 600}
tell ocidNSDictionaryM
####画像のパス
its setObject:targetURL forKey:"theURL"
####ウィンドのサイズ
its setObject:numWidth forKey:"width"
its setObject:numHeight forKey:"height"
end tell
if objMe's NSThread's isMainThread() as boolean then
####Webビューを表示する
my performWebView:ocidNSDictionaryM
else
my performSelectorOnMainThread:"performWebView:" withObject:ocidNSDictionaryM waitUntilDone:true
end if
tell ocidNSDictionaryM
activate
end tell
#####10秒間開いたら閉じる
#####ここでこの処理をしたのはスクリプトメニューからの実行を配慮して
delay 10
end repeat



on performWebView:ocidNSDictionaryM
set {width, height} to {ocidNSDictionaryM's objectForKey:"width", ocidNSDictionaryM's objectForKey:"height"}
set strURL to (ocidNSDictionaryM's objectForKey:"theURL")
########
set theConfiguration to objMe's WKWebViewConfiguration's alloc()'s init()
set ocidURL to objNSURL's URLWithString:strURL
set theFetch to objNSString's stringWithContentsOfURL:ocidURL encoding:(objMe's NSUTF8StringEncoding) |error|:(missing value)
set theUserScript to objMe's WKUserScript's alloc()'s initWithSource:theFetch injectionTime:(objMe's WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
set theUserContentController to objMe's WKUserContentController's alloc()'s init()
theUserContentController's addUserScript:theUserScript
theConfiguration's setUserContentController:theUserContentController
set webViewSize to objMe's NSMakeRect(0, 0, width, height)
set webView to objMe's WKWebView's alloc()'s initWithFrame:webViewSize configuration:theConfiguration
webView's setNavigationDelegate:me
webView's setUIDelegate:me
webView's setTranslatesAutoresizingMaskIntoConstraints:true
set theURL to objMe's |NSURL|'s URLWithString:strURL
set theRequest to objMe's NSURLRequest's requestWithURL:theURL
webView's loadRequest:theRequest
set ocidWebView to webView
########
set listWindowSize to objMe's NSMakeRect(0, 0, width, height)
set numStyleMaskNo to (objMe's NSWindowStyleMaskTitled as integer)
set numStyleMaskNo to numStyleMaskNo + (objMe's NSWindowStyleMaskClosable as integer)
set numStyleMaskNo to numStyleMaskNo + (objMe's NSWindowStyleMaskMiniaturizable as integer)
set numStyleMaskNo to numStyleMaskNo + (objMe's NSWindowStyleMaskResizable as integer)
set ocidWindow to objMe's NSWindow's alloc()'s initWithContentRect:listWindowSize styleMask:numStyleMaskNo backing:2 defer:yes
########
ocidWindow's setContentView:ocidWebView
set ocidNSWindowController to objMe's NSWindowController's alloc()'s initWithWindow:ocidWindow
ocidNSWindowController's showWindow:me
ocidNSWindowController's |window|'s |center|()
ocidNSWindowController's |window|'s makeKeyAndOrderFront:me
tell ocidNSDictionaryM to its setObject:ocidWindow forKey:"window"
end performWebView:


|

[QRCode]Line Out呼び出し用のQRバーコード生成

Img_0130

リンク先がこの画面のQRバーコードを生成します

ダウンロード - lineoutqr.scpt.zip



#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
ラインのURL仕様はこちら
https://developers.line.biz/ja/docs/messaging-api/using-line-url-scheme
*)
#
#
# 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 "CoreImage"
use scripting additions

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
set objFileManager to objMe's NSFileManager's defaultManager()

set strBaseUrlt to "https://line.me/R/call/81/" as text

set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns" as alias
set theResponse to "電話番号を入力" as text
try
set objResponse to (display dialog "電話番号を入力してください" with title "QRコードを作成します" default answer theResponse buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 20 without hidden answer)
on error
log "エラーしました"
return
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
end if
if "OK" is equal to (button returned of objResponse) then
set strText to (text returned of objResponse) as text
else
return "キャンセル"
end if


###フォルダのパス
###ピクチャーフォルダのパス
set aliasDirPath to (path to pictures folder from user domain) as alias
set strDirPath to POSIX path of aliasDirPath as text
####フォルダ名
set strFolderName to "QRcode" as text
set strDirPath to ("" & strDirPath & strFolderName & "") as text
###NSStringテキスト
set ocidDirPath to objNSString's stringWithString:strDirPath
###フォルダを作る
###途中のフォルダも作る-->true
set boolMakeNewFolder to (objFileManager's createDirectoryAtPath:ocidDirPath withIntermediateDirectories:true attributes:(missing value) |error|:(missing value))

####日付フォーマット
set prefDateFormat to "yyyyMMddHHmmss"
set ocidFormatter to objMe's NSDateFormatter's alloc()'s init()
ocidFormatter's setLocale:(objMe's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidFormatter's setDateFormat:(prefDateFormat as string)
set strDateAndTime to (ocidFormatter's stringFromDate:(current date)) as text
#####日付をファイル名にする
set strSaveFilePath to strDirPath & "/" & strDateAndTime & ".png"


################################################################
set strInputText to (strBaseUrlt & strText) as text
####テキストをNSString
set ocidInputString to objNSString's stringWithString:strInputText
################################################################
##全角を半角に変換して
set ocidInputStringHalfwidth to (ocidInputString's stringByApplyingTransform:(objMe's NSStringTransformFullwidthToHalfwidth) |reverse|:false)
##制御文字取り除き
set ocidwhitespaceAndNewlineCharacterSet to objMe's NSCharacterSet's whitespaceAndNewlineCharacterSet
set ocidInputString to ocidInputStringHalfwidth's stringByTrimmingCharactersInSet:ocidwhitespaceAndNewlineCharacterSet
##スペース取り除き
set ocidSearchString to objNSString's stringWithString:" "
set ocidReplacementString to objNSString's stringWithString:""
set ocidTrimmingText to ocidInputString's stringByReplacingOccurrencesOfString:ocidSearchString withString:ocidReplacementString
##ハイフン取り除き
set ocidSearchString to objNSString's stringWithString:"-"
set ocidTrimmingText to ocidTrimmingText's stringByReplacingOccurrencesOfString:ocidSearchString withString:ocidReplacementString
################################################################
####テキストをUTF8
set ocidUtf8InputString to ocidTrimmingText's dataUsingEncoding:(objMe's NSUTF8StringEncoding)
####CIQRCodeGenerator初期化
set ocidQRcodeImage to objMe's CIFilter's filterWithName:"CIQRCodeGenerator"
ocidQRcodeImage's setDefaults()
###テキスト設定
ocidQRcodeImage's setValue:ocidUtf8InputString forKey:"inputMessage"
###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:"Q" forKey:"inputCorrectionLevel"
###QRコード本体のイメージ
set ocidCIImage to ocidQRcodeImage's outputImage()
-->ここで生成されるのはQRのセルが1x1pxの最小サイズ
###QRコードの縦横取得
set ocidCIImageDimension to ocidCIImage's extent()
set ocidCIImageWidth to (item 1 of item 2 of ocidCIImageDimension) as integer
set ocidCIImageHight to (item 2 of item 2 of ocidCIImageDimension) as integer
###最終的に出力したいpxサイズ
set numScaleMax to 580
###整数で拡大しないとアレなのでの値のニアなサイズになります
set numWidth to ((numScaleMax / ocidCIImageWidth) div 1) as integer
set numHight to ((numScaleMax / ocidCIImageHight) div 1) as integer
###↑サイズの拡大縮小する場合はここで値を調整すれば良い
####変換スケール作成-->拡大
set recordScalse to objMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:recordScalse
#######元のセルが1x1pxの最小サイズで出したいときはここで処理
##set ocidCIImageScaled to ocidCIImage
###イメージデータを展開
set ocidNSCIImageRep to objMe's NSCIImageRep's imageRepWithCIImage:ocidCIImageScaled
###出力用のイメージの初期化
set ocidNSImageScaled to objMe's NSImage's alloc()'s initWithSize:(ocidNSCIImageRep's |size|())
###イメージデータを合成
ocidNSImageScaled's addRepresentation:ocidNSCIImageRep
###出来上がったデータはOS_dispatch_data
set ocidOsDispatchData to ocidNSImageScaled's TIFFRepresentation()
####NSBitmapImageRep
set ocidNSBitmapImageRep to objMe's NSBitmapImageRep's imageRepWithData:ocidOsDispatchData
#################################################################
###quiet zone用に画像をパディングする
set numPadWidth to ((ocidCIImageWidth * numWidth) + (numWidth * 6)) as integer
set numPadHight to ((ocidCIImageHight * numHight) + (numHight * 6)) as integer
###左右に4セル分づつ余白 quiet zoneを足す
####まずは元のQRコードのサイズに8セルサイズ分足したサイズの画像を作って
set ocidNSBitmapImagePadRep to (objMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:numPadWidth pixelsHigh:numPadHight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(objMe's NSCalibratedRGBColorSpace) bitmapFormat:(objMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
###初期化
objMe's NSGraphicsContext's saveGraphicsState()
###ビットマップイメージ
(objMe's NSGraphicsContext's setCurrentContext:(objMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:ocidNSBitmapImagePadRep))
###塗り色を『白』に指定して
objMe's NSColor's whiteColor()'s |set|()
###画像にする
objMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}})
###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
ocidNSBitmapImageRep's drawInRect:{origin:{x:(numWidth * 3), y:(numHight * 3)}, |size|:{width:numPadWidth, Hight:numPadHight}} fromRect:{origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}} operation:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
####画像作成終了
objMe's NSGraphicsContext's restoreGraphicsState()

#################################################################
####JPEG用の圧縮プロパティ
##set ocidNSSingleEntryDictionary to objMe's NSDictionary's dictionaryWithObject:1 forKey:(objMe's NSImageCompressionFactor)
####PNG用の圧縮プロパティ
set ocidNSSingleEntryDictionary to objMe's NSDictionary's dictionaryWithObject:true forKey:(objMe's NSImageInterlaced)

#####出力イメージへ変換
set ocidNSInlineData to (ocidNSBitmapImagePadRep's representationUsingType:(objMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
(*
NSBitmapImageFileTypeJPEG
NSBitmapImageFileTypePNG
NSBitmapImageFileTypeGIF
NSBitmapImageFileTypeBMP
NSBitmapImageFileTypeTIFF
NSBitmapImageFileTypeJPEG2000
*)
######インラインデータをファイルに書き出し
set boolMakeQrCode to (ocidNSInlineData's writeToFile:strSaveFilePath atomically:true)

###################
###ここから出来上がったファイルについて
set aliasDirPath to POSIX file strDirPath as alias
###
tell application "Finder"
select aliasDirPath
end tell
###
tell application "Preview"
launch
activate
tell window 1
open (POSIX file strSaveFilePath as alias)
end tell
end tell

return true

|

[Map]位置情報をQRコードにするv2

[Map]位置情報をQRコードにする
https://quicktimer.cocolog-nifty.com/icefloe/2022/04/post-af06ee.html
こちらのアップデートです。
現時点ではここまでにしょうか…と
NSMutableDictionaryを使ってみたものの…
処理は煩雑になるわ、テキスト形式に戻すのに記述が増えるは…で
あまり良い事なかった。
1:便利な機能は使っていく
2:記述にこだわらず、可読性や処理のシンプルさが結局後で効く

こだわらずに、最適と思われる方法にすればよかったなぁ…遠い目
(読みにくいわ…修正しにくいわで、最低な出来だと…トホホ)



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
009##自分環境がos12なので2.8にしているだけです
010use AppleScript version "2.8"
011use framework "Foundation"
012use framework "CoreImage"
013use scripting additions
014
015property objMe : a reference to current application
016property objNSString : a reference to objMe's NSString
017property objNSURL : a reference to objMe's NSURL
018##
019property objNSDictionary : a reference to objMe's NSDictionary
020property objNSMutableDictionary : a reference to objMe's NSMutableDictionary
021property objNSArray : a reference to objMe's NSArray
022property objNSMutableArray : a reference to objMe's NSMutableArray
023
024set objFileManager to objMe's NSFileManager's defaultManager()
025
026###リセット
027set theURL to "" as text
028set ocidNSInlineData to "" as text
029set ocidNSBitmapImagePadRep to "" as text
030
031tell application "Finder"
032  set the clipboard to the theURL as string
033end tell
034
035objMe's NSLog("■:osascript:Start Script Geo2Qr4Map")
036
037###コピーのサブへ
038doCopyMap()
039
040log "theURL:" & theURL
041objMe's NSLog("■:osascript:コピー OK" & theURL & "")
042###クリップボードからURLを取得する
043tell application "Finder"
044  set theURL to (the clipboard) as text
045end tell
046delay 0.5
047
048##################################################
049objMe's NSLog("■:osascript: theURL" & theURL & "")
050set strURL to theURL as text
051
052##################################################
053if strURL is "" then
054  ###URLの取得に失敗しているパターン
055  set aliasIconPath to POSIX file "/System/Applications/Maps.app/Contents/Resources/AppIcon.icns" as alias
056  set strDefaultAnswer to "https://maps.apple.com/?ll=35.658558,139.745504" as text
057  try
058    set objResponse to (display dialog "URLの取得に失敗しました" with title "QRテキスト" default answer strDefaultAnswer buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 20 without hidden answer)
059  on error
060    log "エラーしました"
061    return
062  end try
063  if true is equal to (gave up of objResponse) then
064    return "時間切れですやりなおしてください"
065  end if
066  if "OK" is equal to (button returned of objResponse) then
067    set strURL to (text returned of objResponse) as text
068  else
069    return "キャンセル"
070  end if
071end if
072
073############################
074##値がコピー出来なかったときエラーになるので
075##ここはトライ
076try
077  ####################################
078  ###URLをNSURLに格納
079  set ocidURL to objNSURL's alloc's initWithString:strURL
080  log className() of ocidURL as text
081  --> NSURL
082  ####################################
083  ###クエリー部を取り出し
084  set ocidQueryUrl to ocidURL's query
085  log className() of ocidQueryUrl as text
086  --> __NSCFString
087  log ocidQueryUrl as text
088on error
089###エラーしたらコピー取り直し
090  doCopyMap()
091  tell application "Finder"
092    set theURL to (the clipboard) as text
093  end tell
094  ####################################
095  ###URLをNSURLに格納
096  set ocidURL to objNSURL's alloc's initWithString:strURL
097  log className() of ocidURL as text
098  --> NSURL
099  ####################################
100  ###クエリー部を取り出し
101  set ocidQueryUrl to ocidURL's query
102  log className() of ocidQueryUrl as text
103  --> __NSCFString
104  log ocidQueryUrl as text
105end try
106
107####################################
108###取り出したクエリを&を区切り文字でリストに
109set ocidArrayComponent to (ocidQueryUrl's componentsSeparatedByString:"&")
110log className() of ocidArrayComponent as text
111--> __NSArrayM
112log ocidArrayComponent as list
113
114####################################
115####可変レコードを作成
116set ocidRecordQuery to objNSMutableDictionary's alloc()'s init()
117####値が空のレコードを定義
118set recordQuery to {t:"", q:"", address:"", near:"", ll:"", z:"18", spn:"", saddr:"", daddr:"", dirflg:"", sll:"", sspn:"", ug:""} as record
119####↑の定義で値が空の可変レコードを作成
120set ocidRecordQuery to objNSMutableDictionary's dictionaryWithDictionary:recordQuery
121####################################
122###ここからクエリー分繰り返し
123repeat with objArrayComponent in ocidArrayComponent
124  #####渡されたクエリーを=を境に分割してArray=リストにする
125  set ocidArrayFirstObject to (objArrayComponent's componentsSeparatedByString:"=")
126  
127  ####まずは順番に キー と 値 で格納
128  set ocidKey to item 1 of ocidArrayFirstObject
129  log ocidKey as text
130  
131  set ocidValue to item 2 of ocidArrayFirstObject
132  log ocidValue as text
133  
134  #########位置情報 緯度 経度
135  if (ocidKey as text) = "ll" then
136    set ll of ocidRecordQuery to ocidValue
137    ####カンマでわけて緯度 経度に
138    set ocidArrayLL to (ocidValue's componentsSeparatedByString:",")
139    log ocidArrayLL as list
140    ###最初の項目
141    set ocidLatitude to item 1 of ocidArrayLL
142    log "Latitude:" & ocidLatitude as text
143    ###あとの項目
144    set ocidLongitude to item 2 of ocidArrayLL
145    log "Longitude:" & ocidLongitude as text
146    
147    #########Address String  住所
148  else if (ocidKey as text) = "address" then
149    set address of ocidRecordQuery to ocidValue
150    set ocidAddEnc to ocidValue's stringByRemovingPercentEncoding
151    log "AddressString:" & ocidAddEnc as text
152    
153    #########The zoom level. 高さ方向
154  else if (ocidKey as text) = "z" then
155    set z of ocidRecordQuery to ocidValue
156    set ocidZoomValue to ocidValue
157    log "ZoomValue:" & ocidZoomValue
158    
159    #########マップビュー
160  else if (ocidKey as text) = "t" then
161    set t of ocidRecordQuery to ocidValue
162    set ocidMapType to ocidValue
163    log "MapType:" & ocidMapType
164    (*
165    m (standard view)
166    k (satellite view)
167    h (hybrid view)
168    r (transit view)
169    goole
170    map_action=pano
171    map_action=map
172    basemap=satellite
173    terrain
174    roadmap
175    *)
176    ####################################
177    #########dirflg 移動方法  
178  else if (ocidKey as text) = "dirflg" then
179    set dirflg of ocidRecordQuery to ocidValue
180    set ocidDirflgType to ocidValue
181    log "DirflgType:" & ocidDirflgType
182    (*
183    d (by car)
184    w (by foot)
185    r (by public transit)
186    
187    goole
188    travelmode=driving
189    walking
190    transit
191      *)
192    
193    #########Dirflg Parameters 出発点
194  else if (ocidKey as text) = "saddr" then
195    set saddr of ocidRecordQuery to ocidValue
196    set strSaddrEnc to ocidValue as text
197    set ocidSaddrEnc to ocidValue's stringByRemovingPercentEncoding
198    log "StartingPoint:" & ocidSaddrEnc as text
199    
200    #########Destination  到着店
201  else if (ocidKey as text) = "daddr" then
202    set daddr of ocidRecordQuery to ocidValue
203    set strDaddrEnc to ocidValue as text
204    set ocidDaddrEnc to ocidValue's stringByRemovingPercentEncoding
205    log "DestinationPoint:" & ocidDaddrEnc as text
206    
207    #########Search Query 検索語句
208  else if (ocidKey as text) = "q" then
209    set q of ocidRecordQuery to ocidValue
210    set strRecordQuery to ocidValue as text
211    set ocidSearchQueryEnc to ocidValue's stringByRemovingPercentEncoding
212    log "SearchQuery" & ocidSearchQueryEnc as text
213    
214    ####################################
215    #########語句検索時の周辺情報の有無による分岐
216    
217  else if (ocidKey as text) = "sll" then
218    set sll of ocidRecordQuery to ocidValue
219    ####カンマでわけて緯度 経度に
220    set ocidSearchArrayLL to (ocidValue's componentsSeparatedByString:",")
221    log ocidSearchArrayLL as list
222    ####最初の項目
223    set ocidNearLatitude to item 1 of ocidSearchArrayLL
224    log "NearLatitude:" & ocidNearLatitude as text
225    ####あとの項目
226    set ocidNearLongitude to item 2 of ocidSearchArrayLL
227    log "NearNearLongitude:" & ocidNearLongitude as text
228    
229  else if (ocidKey as text) = "spn" then
230    ####周囲情報の範囲
231    set spn of ocidRecordQuery to ocidValue
232    
233    
234    ####################################
235    #########during search周辺 位置情報 緯度 経度
236    
237  else if (ocidKey as text) = "near" then
238    set near of ocidRecordQuery to ocidValue
239    ####カンマでわけて緯度 経度に
240    set ocidNearArrayLL to (ocidValue's componentsSeparatedByString:",")
241    log ocidNearArrayLL as list
242    ###最初の項目
243    set ocidNearLatitude to item 1 of ocidNearArrayLL
244    log "NearLatitude:" & ocidNearLatitude as text
245    ###あとの項目
246    set ocidNearLongitude to item 2 of ocidNearArrayLL
247    log "NearNearLongitude:" & ocidNearLongitude as text
248    
249    ####################################
250    #########ガイド時のug
251  else if (ocidKey as text) = "ug" then
252    set ug of ocidRecordQuery to ocidValue
253    
254  end if
255  
256end repeat
257
258log ocidRecordQuery as record
259objMe's NSLog("■:osascript: RecordQuery Done")
260#####################################################
261#####QRコード保存要ファイル名
262if (q of ocidRecordQuery as text) is not "" then
263  ###検索語句あり
264  if (count of (ocidSearchQueryEnc as text)) < 8 then
265    set strQueryEnc to (ocidSearchQueryEnc as text) as text
266  else
267    set strQueryEnc to characters 1 thru 8 of (ocidSearchQueryEnc as text) as text
268  end if
269  set strFileName to ("" & strQueryEnc & ".png")
270  objMe's NSLog("■:osascript: ocidSearchQueryEnc " & (ocidSearchQueryEnc as text) & "")
271  
272else if (daddr of ocidRecordQuery as text) is not "" then
273  ###行き先語句あり
274  set strDaddrEnc to characters 1 thru 8 of (ocidDaddrEnc as text) as text
275  set strFileName to ("" & strDaddrEnc & ".png")
276  objMe's NSLog("■:osascript: ocidDaddrEnc " & (ocidDaddrEnc as text) & "")
277else
278  ###語句の無い場合は日付をファイル名にする
279  set strDateFormat to "yyyy年MMMMdd日hh時mm分" as text
280  set ocidForMatter to objMe's NSDateFormatter's alloc()'s init()
281  ocidForMatter's setLocale:(objMe's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
282  ocidForMatter's setDateFormat:(strDateFormat)
283  set objDate to (current date)
284  set strDateTime to (ocidForMatter's stringFromDate:(objDate)) as text
285  set strFileName to ("" & strDateTime & ".png")
286end if
287
288####################################################
289#########対応アプリの分岐
290###ホスト名を取り出し
291set ocidHostUrl to ocidURL's |host|
292log className() of ocidHostUrl as text
293--> __NSCFString
294log ocidHostUrl as text
295####################################
296###ホストによる分岐
297if (ocidHostUrl as text) is "guides.apple.com" then
298  -->このままの値でバーコードを作成する
299  set listButtonAset to {"AppleMapガイド用"} as list
300  set strAlertMes to "ガイドリンクはAppleMap専用です"
301  
302else if (ocidHostUrl as text) is "collections.apple.com" then
303  -->コレクションは現在は『ガイド』になった?
304  set listButtonAset to {"AppleMapガイド用"} as list
305  set strAlertMes to "ガイドリンクはAppleMap専用です"
306  
307else if (ocidHostUrl as text) is "maps.apple.com" then
308  -->ガイド以外
309  -->処理する
310  ####################################
311  ###内容によっての分岐
312  if (ll of ocidRecordQuery as text) is not "" then
313    ######緯度経度がある場合
314    set listButtonAset to {"AppleMap用", "GoogleMap用", "GeoQR"} as list
315    set strAlertMes to "GeoQRは対応していない機種やアプリがあります"
316    
317  else if (q of ocidRecordQuery as text) is not "" then
318    ######検索語句がある場合
319    set listButtonAset to {"AppleMap用", "GoogleMap用", "汎用"} as list
320    set strAlertMes to "iOS用AppleMapのQRコードを作成する OR 一般的なQRコードを作成する"
321    
322  else if (daddr of ocidRecordQuery as text) is not "" then
323    set listButtonAset to {"AppleMap経路", "GoogleMap経路"} as list
324    set strAlertMes to "経路情報用のMapになります"
325    
326  else
327    ######緯度経度無し検索語句無しだとAppleMapのみ
328    set listButtonAset to {"AppleMap用のみ"} as list
329    set strAlertMes to "ガイドリンクはAppleMap専用です"
330    
331  end if
332end if
333##############################################
334log listButtonAset
335try
336  set objAns to (display alert "どちら用のQRコードを作成しますか?" message strAlertMes default button 1 buttons listButtonAset)
337on error
338  log "エラーしました"
339  return
340end try
341
342set objResponse to (button returned of objAns) as text
343##############################################
344
345if objResponse is "GeoQR" then
346  ### 緯度経度でGEOバーコード 対応機種に制限がある場合あり
347  set theChl to ("GEO:" & (ocidLatitude as text) & "," & (ocidLongitude as text) & "," & (z of ocidRecordQuery as text) & "") as text
348  ###経路情報 Map
349else if objResponse is "AppleMap経路" then
350  set theChl to ("http://maps.apple.com/?daddr=" & (ocidDaddrEnc as text) & "&saddr=" & (ocidSaddrEnc as text) & "") as text
351  ###経路情報 Google
352else if objResponse is "GoogleMap経路" then
353  set theChl to ("https://www.google.com/maps/?daddr=" & (ocidDaddrEnc as text) & "&saddr=" & (ocidSaddrEnc as text) & "") as text
354  ####AppleMapのガイドリンク
355else if objResponse is "AppleMapガイド用" then
356  set theChl to ("" & strURL & "") as text
357  
358else if objResponse is "GoogleMap用" then
359  ##############################################
360  ###GoogleMap用の小数点以下の桁揃え
361  set theLatitude to (ocidLatitude as text)
362  set AppleScript's text item delimiters to "."
363  set listLatitude to every text item of theLatitude as list
364  set AppleScript's text item delimiters to ""
365  set strLatitudeInt to text item 1 of listLatitude as text
366  set strLatitudeDecimal to text item 2 of listLatitude as text
367  set strLatitudeDecimal to (text 1 through 7 of (strLatitudeDecimal & "000000000")) as text
368  set theLatitude to ("" & strLatitudeInt & "." & strLatitudeDecimal & "")
369  
370  set theLongitude to (ocidLongitude as text)
371  set AppleScript's text item delimiters to "."
372  set listLongitude to every text item of theLongitude as list
373  set AppleScript's text item delimiters to ""
374  set strLongitudeInt to text item 1 of listLongitude as text
375  set strLongitudeDecimal to text item 2 of listLongitude as text
376  set strLongitudeDecimal to (text 1 through 7 of (strLongitudeDecimal & "000000000")) as text
377  set theLongitude to ("" & strLongitudeInt & "." & strLongitudeDecimal & "")
378  
379  set theGooglemapParts to ("@" & theLatitude & "," & theLongitude & "," & (z of ocidRecordQuery as text) & "z")
380  
381  set theChl to ("https://www.google.com/maps/" & theGooglemapParts & "") as text
382else
383  set theChl to ("http://maps.apple.com/?q=" & (ocidLatitude as text) & "," & (ocidLongitude as text) & "," & (z of ocidRecordQuery as text) & "z") as text
384end if
385
386
387##############################################
388log theChl
389
390###フォルダのパス
391###ピクチャーフォルダのパス
392tell application "Finder"
393  set aliasDirPath to (path to pictures folder from user domain) as alias
394  set strDirPath to POSIX path of aliasDirPath as text
395end tell
396####フォルダ名
397set strFolderName to "QRcode" as text
398set strDirPath to ("" & strDirPath & strFolderName & "") as text
399###NSStringテキスト
400set ocidDirPath to objNSString's stringWithString:strDirPath
401###フォルダを作る
402###途中のフォルダも作る-->true
403set boolMakeNewFolder to (objFileManager's createDirectoryAtPath:ocidDirPath withIntermediateDirectories:true attributes:(missing value) |error| :(missing value))
404
405####ファイルパス
406set strSaveFilePath to ("" & strDirPath & "/" & strFileName & "") as text
407
408objMe's NSLog("■:osascript: strSaveFilePath" & strSaveFilePath & "")
409
410##############################################
411set strInputText to theChl as text
412####テキストをNSStringに
413set ocidInputString to objNSString's stringWithString:strInputText
414####テキストをUTF8に
415set ocidUtf8InputString to ocidInputString's dataUsingEncoding:(objMe's NSUTF8StringEncoding)
416####CIQRCodeGenerator初期化
417set ocidQRcodeImage to objMe's CIFilter's filterWithName:"CIQRCodeGenerator"
418ocidQRcodeImage's setDefaults()
419###テキスト設定
420ocidQRcodeImage's setValue:ocidUtf8InputString forKey:"inputMessage"
421###読み取り誤差値設定L, M, Q, H
422ocidQRcodeImage's setValue:"Q" forKey:"inputCorrectionLevel"
423###QRコード本体のイメージ
424set ocidCIImage to ocidQRcodeImage's outputImage()
425-->ここで生成されるのはQRのセルが1x1pxの最小サイズ
426###QRコードの縦横取得
427set ocidCIImageDimension to ocidCIImage's extent()
428set ocidCIImageWidth to (item 1 of item 2 of ocidCIImageDimension) as integer
429set ocidCIImageHight to (item 2 of item 2 of ocidCIImageDimension) as integer
430###最終的に出力したいpxサイズ
431set numScaleMax to 720
432###整数で拡大しないとアレなので↑の値のニアなサイズになります
433set numWidth to ((numScaleMax / ocidCIImageWidth) div 1) as integer
434set numHight to ((numScaleMax / ocidCIImageHight) div 1) as integer
435###↑サイズの拡大縮小する場合はここで値を調整すれば良い
436####変換スケール作成-->拡大
437set recordScalse to objMe's CGAffineTransform's CGAffineTransformMakeScale(numWidth, numHight)
438##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
439set ocidCIImageScaled to ocidCIImage's imageByApplyingTransform:recordScalse
440#######元のセルが1x1pxの最小サイズで出したいときはここで処理
441##set ocidCIImageScaled to ocidCIImage
442###イメージデータを展開
443set ocidNSCIImageRep to objMe's NSCIImageRep's imageRepWithCIImage:ocidCIImageScaled
444###出力用のイメージの初期化
445set ocidNSImageScaled to objMe's NSImage's alloc()'s initWithSize:(ocidNSCIImageRep's |size|())
446###イメージデータを合成
447ocidNSImageScaled's addRepresentation:ocidNSCIImageRep
448###出来上がったデータはOS_dispatch_data
449set ocidOsDispatchData to ocidNSImageScaled's TIFFRepresentation()
450####NSBitmapImageRepに
451set ocidNSBitmapImageRep to objMe's NSBitmapImageRep's imageRepWithData:ocidOsDispatchData
452#################################################################
453###quiet zone用に画像をパディングする
454set numPadWidth to ((ocidCIImageWidth * numWidth) + (numWidth * 6)) as integer
455set numPadHight to ((ocidCIImageHight * numHight) + (numHight * 6)) as integer
456###左右に3セル分づつ余白 quiet zoneを足す
457####まずは元のQRコードのサイズに6セルサイズ分足したサイズの画像を作って
458set ocidNSBitmapImagePadRep to (objMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:numPadWidth pixelsHigh:numPadHight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(objMe's NSCalibratedRGBColorSpace) bitmapFormat:(objMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
459###初期化
460objMe's NSGraphicsContext's saveGraphicsState()
461###ビットマップイメージ
462(objMe's NSGraphicsContext's setCurrentContext:(objMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:ocidNSBitmapImagePadRep))
463###塗り色を『白』に指定して
464objMe's NSColor's whiteColor()'s |set|()
465##画像にする
466objMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}})
467###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
468ocidNSBitmapImageRep's drawInRect:{origin:{x:(numWidth * 3), y:(numHight * 3)}, |size|:{width:numPadWidth, Hight:numPadHight}} fromRect:{origin:{x:0, y:0}, |size|:{width:numPadWidth, height:numPadHight}} operation:(objMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
469####画像作成終了
470objMe's NSGraphicsContext's restoreGraphicsState()
471objMe's NSLog("■:osascript: restoreGraphicsState")
472#################################################################
473
474####JPEG用の圧縮プロパティ
475##set ocidNSSingleEntryDictionary to objMe's NSDictionary's dictionaryWithObject:1 forKey:(objMe's NSImageCompressionFactor)
476####PNG用の圧縮プロパティ
477set ocidNSSingleEntryDictionary to objMe's NSDictionary's dictionaryWithObject:true forKey:(objMe's NSImageInterlaced)
478
479#####出力イメージへ変換
480set ocidNSInlineData to (ocidNSBitmapImagePadRep's representationUsingType:(objMe's NSBitmapImageFileTypePNG) |properties|:ocidNSSingleEntryDictionary)
481
482######インラインデータをファイルに書き出し
483set boolMakeQrCode to (ocidNSInlineData's writeToFile:strSaveFilePath atomically:true)
484
485set aliasDirPath to POSIX file strDirPath as alias
486###保存場所を開いて
487tell application "Finder"
488  select aliasDirPath
489end tell
490####プレビューに表示
491tell application "Preview"
492  launch
493  activate
494  open aliasDirPath
495end tell
496
497objMe's NSLog("■:osascript: Done")
498set theURL to ""
499set the clipboard to theURL
500set ocidNSInlineData to ""
501set ocidNSBitmapImagePadRep to ""
502
503
504return true
505
506
507to doCopyMap()
508  tell application "System Events"
509    launch
510  end tell
511  tell application "Maps"
512    activate
513  end tell
514  try
515    tell application "System Events"
516      tell process "Maps"
517        ##  get every menu bar
518        tell menu bar 1
519          ##  get every menu bar item
520          tell menu bar item "編集"
521            ##  get every menu bar item
522            tell menu "編集"
523              ##  get every menu item
524              tell menu item "リンクをコピー"
525                click
526              end tell
527            end tell
528          end tell
529        end tell
530      end tell
531    end tell
532  on error
533    tell application "System Events"
534      tell process "Maps"
535        get every menu bar
536        tell menu bar 1
537          get every menu bar item
538          tell menu bar item "編集"
539            get every menu bar item
540            tell menu "編集"
541              get every menu item
542              tell menu item "コピー"
543                click
544              end tell
545            end tell
546          end tell
547        end tell
548      end tell
549    end tell
550  end try
551end doCopyMap
AppleScriptで生成しました

|

その他のカテゴリー

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