I want to resize an NSImage from 512px to 60px, I found only the code for iOS, but nothing for OSX.
Asked
Active
Viewed 6,783 times
7
-
[This](http://stackoverflow.com/a/30422317/5328140) answer works perfectly fine for me – Jonas W Jan 19 '16 at 21:01
1 Answers
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
-
12The `NSImage(data: newImage.TIFFRepresentation!)!` part wastes a lot of resources for no reason, just `return newImage`. – DarkDust Mar 02 '18 at 14:21