Archive for the 'NSGraphicsContext' Category

2017/02/03 倍率を指定して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”

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:

on saveNSImageAtPathAsPNG(anImage, outPath)
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