CoreGraphics resizing function from iOS (UIImage) to MacOS (NSImage)

Goal:
Rewrite CoreGraphics resizing function from iOS (UIImage) to MacOS (NSImage)


Problem:
Getting error on this line of code: let bytesPerPixel = cgImage.bitsPerPixel / bitsPerComponent

Error: Value of type '(UnsafeMutablePointer?, NSGraphicsContext?, [NSImageRep.HintKey : Any]?) -> CGImage?' (aka '(Optional<UnsafeMutablePointer>, Optional, Optional<Dictionary<NSImageRep.HintKey, Any>>) -> Optional') has no member 'bitsPerPixel'

Question: how can I replace "cgImage.bitsPerPixel" for something that works with NSImage?


iOS: UIImage

Code Block
extension UIImage {
// Resizeing using CoreGraphics
func resize(to size:CGSize) -> UIImage? {
let cgImage = self.cgImage!
let destWidth = Int(size.width)
let destHeight = Int(size.height)
let bitsPerComponent = 8
let bytesPerPixel = cgImage.bitsPerPixel / bitsPerComponent
let destBytesPerRow = destWidth * bytesPerPixel
let context = CGContext(data: nil,
width: destWidth,
height: destHeight,
bitsPerComponent: bitsPerComponent,
bytesPerRow: destBytesPerRow,
space: cgImage.colorSpace!,
bitmapInfo: cgImage.bitmapInfo.rawValue)!
context.interpolationQuality = .high
context.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: size))
return context.makeImage().flatMap { UIImage(cgImage: $0) }
}
}

MacOS: NSImage
Code Block
extension NSImage {
// Resizeing using CoreGraphics
func resize(to size:CGSize) -> NSImage? {
let cgImage = self.cgImage
let destWidth = Int(size.width)
let destHeight = Int(size.height)
let bitsPerComponent = 8
let bytesPerPixel = cgImage.bitsPerPixel / bitsPerComponent
let destBytesPerRow = destWidth * bytesPerPixel
let context = CGContext(data: nil,
width: destWidth,
height: destHeight,
bitsPerComponent: bitsPerComponent,
bytesPerRow: destBytesPerRow,
space: cgImage.colorSpace!,
bitmapInfo: cgImage.bitmapInfo.rawValue)!
context.interpolationQuality = .high
context.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: size))
return context.makeImage().flatMap { NSImage(cgImage: $0) }
}
}

The problem is that NSImage doesn't have the .cgImage accessor that UIImage has. It is a function with optional parameters, so to get the CGImage from an NSImage you need to do this instead:
Code Block swift
let cgImage = self.cgImage()


CoreGraphics resizing function from iOS (UIImage) to MacOS (NSImage)
 
 
Q