7

I want to resize an NSImage from 512px to 60px, I found only the code for iOS, but nothing for OSX.

Tomas.1997
  • 173
  • 2
  • 5

1 Answers1

19

I found a function on GitHub, it is working fine for me.

func resize(image: NSImage, w: Int, h: Int) -> NSImage {
    var destSize = NSMakeSize(CGFloat(w), CGFloat(h))
    var newImage = NSImage(size: destSize)
    newImage.lockFocus()
    image.drawInRect(NSMakeRect(0, 0, destSize.width, destSize.height), fromRect: NSMakeRect(0, 0, image.size.width, image.size.height), operation: NSCompositingOperation.CompositeSourceOver, fraction: CGFloat(1))
    newImage.unlockFocus()
    newImage.size = destSize
    return NSImage(data: newImage.TIFFRepresentation!)!
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Sandeep Joshi
  • 316
  • 3
  • 6
  • 12
    The `NSImage(data: newImage.TIFFRepresentation!)!` part wastes a lot of resources for no reason, just `return newImage`. – DarkDust Mar 02 '18 at 14:21