LoginSignup
7
7

More than 5 years have passed since last update.

NSImage をリサイズする

Posted at

目的

OS X アプリで、NSImage 型で表現された画像データをリサイズした画像を、次のようにして作成してみました。

ソースコード

NSImage 型の変数 sourceImage に格納されている画像を、NSSize 型の変数 newSize に格納したサイズにリサイズします。

// sourceImage から NSBitmapImageRep を取得して、そこから CGImage を取り出します。
let image = NSBitmapImageRep(data: sourceImage.TIFFRepresentation!)?.CGImage!

// 新しいサイズのビットマップを作成します。
let width = UInt(newSize.width)
let height = UInt(newSize.height)
let bitsPerComponent = UInt(8)
let bytesPerRow = UInt(4) * width
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)

let bitmapContext = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)!

// 元画像 (image) をビットマップに書き出します。
let bitmapRect = NSMakeRect(0.0, 0.0, newSize.width, newSize.height)

CGContextDrawImage(bitmapContext, bitmapRect, image)

// ビットマップを NSImage に変換します。
let newImageRef = CGBitmapContextCreateImage(bitmapContext)!
let newImage = NSImage(CGImage: newImageRef, size: newSize)

コードの内容

新しいサイズの画像コンテキストを CGBitmapContextCreate 関数で作成して、そこに CGContextDrawImage 関数を使って元画像を書き出しています。

書き出した画像を CGBitmapContextCreateImage を使って CGImage 形式のデータに書き出し、それを使って NSImage を組み立てています。


[詳細] http://ez-net.jp/article/27/DY0R3-1O/SJQQ_0rAOV6B/

ブログでは他のコードで実現しようとして失敗したお話も備忘録として記してあります。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7