Archive for the 'NSGraphicsContext' Category

2017/02/03 倍率を指定してNSImageをリサイズする

与えられたNSImageをリサイズするAppleScriptです。

実行サンプルとして、実行中のコンピュータの画像(NSImageNameComputer)をNSImageで取得、このNSImageを16倍の大きさにリサイズし、指定場所&名称でPNG形式で保存します。

AppleScript名:NSImageの倍率を変更してNSImageをリサイズする
– Created 2017-02-03 by Takaaki Naganoya
– 2017 Piyomaru Software
use AppleScript version “2.4″
use scripting additions
use framework “Foundation”
use framework “AppKit”
–http://stackoverflow.com/questions/11949250/how-to-resize-nsimage
–http://piyocast.com/as/archives/4437

set aPath to POSIX path of (choose file name with prompt “Enter PNG file name”)

–Get Computer Icon
set anImage to current application’s NSImage’s imageNamed:(current application’s NSImageNameComputer)

–Resize it to x16
set resizedImg to my resizedImage:anImage toScale:16
set aRes to saveNSImageAtPathAsPNG(resizedImg, aPath) of me

on resizedImage:aSourceImg toScale:imgScale
  if (aSourceImg’s isValid()) as boolean = false then error “Invalid NSImage”
  
  
set aSize to aSourceImg’s |size|()
  
–>  {width:32.0, height:32.0}
  
  
set aWidth to (aSize’s width) * imgScale
  
set aHeight to (aSize’s height) * imgScale
  
  
set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:aWidth pixelsHigh:aHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(current application’s NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0
  
  
set newSize to {width:aWidth, height:aHeight}
  
aRep’s setSize:newSize
  
  
current application’s NSGraphicsContext’s saveGraphicsState()
  
current application’s NSGraphicsContext’s setCurrentContext:(current application’s NSGraphicsContext’s graphicsContextWithBitmapImageRep:aRep)
  
  
aSourceImg’s drawInRect:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeCopy) fraction:(1.0)
  
  
current application’s NSGraphicsContext’s restoreGraphicsState()
  
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:newSize
  
newImg’s addRepresentation:aRep
  
  
return newImg
end resizedImage:toScale:

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  –画像のRaw画像を作成
  
set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
  
–書き出しファイルパス情報を作成
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
  
–書き出し
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

★Click Here to Open This Script