Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SKaplanOfficial/ec3e64b0dd493483ef41bb14b4e5944d to your computer and use it in GitHub Desktop.
Save SKaplanOfficial/ec3e64b0dd493483ef41bb14b4e5944d to your computer and use it in GitHub Desktop.
NSImage class extension method for resizing NSImages to specific pixel dimensions instead of points.
public extension NSImage {
/// Resizes the image to the specified pixel dimensions.
/// - Parameter newSize: The width and height (in pixels) to resize the image to.
func resize(to newSize: NSSize) -> NSImage {
guard let rep = 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) else {
assertionFailure("Could not create NSBitmapImageRep")
return self
}
rep.size = newSize
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
let rect = NSRect(origin: .zero, size: newSize)
self.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
NSGraphicsContext.restoreGraphicsState()
let resizedImage = NSImage(size: newSize)
resizedImage.addRepresentation(rep)
return resizedImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment