I wanted a simple function to resize an image to a desired height, while keeping proportions. Here’s what I came up with (based on Marco implementation):

extension NSImage {

func resizedImageTo(sourceImage: NSImage, newSize: NSSize) -> NSImage?{

if sourceImage.isValid == false {

return nil

}

let representation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(newSize.width), pixelsHigh: Int(newSize.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0)

representation?.size = newSize

NSGraphicsContext.saveGraphicsState()

NSGraphicsContext.current = NSGraphicsContext.init(bitmapImageRep: representation!)

sourceImage.draw(in: NSRect(x: 0, y: 0, width: newSize.width, height: newSize.height), from: NSZeroRect, operation: .copy, fraction: 1.0)

NSGraphicsContext.restoreGraphicsState()

let newImage = NSImage(size: newSize)

newImage.addRepresentation(representation!)

return newImage

}

}

Questions / comments / suggestions? I’m at @MarcMasVi

Marc

*Updated after I discovered the great implementation Marco Arment suggested. *