« Numbers全セル巡回 | トップページ | [Edge]URLを開く »

画像のリサイズ(解像度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


|

« Numbers全セル巡回 | トップページ | [Edge]URLを開く »

AppleScript NSImage」カテゴリの記事