Skip to content

Instantly share code, notes, and snippets.

@eugenebokhan
Created March 12, 2020 13:45
Show Gist options
  • Save eugenebokhan/ee352f2f96bd0027c082694138c3777c to your computer and use it in GitHub Desktop.
Save eugenebokhan/ee352f2f96bd0027c082694138c3777c to your computer and use it in GitHub Desktop.
import CoreGraphics
extension CGImage {
func grayscalePixelData() -> [UInt8] {
let startTime = CACurrentMediaTime()
let size = CGSize(width: self.width,
height: self.height)
let dataSize = size.width * size.height
var pixelData = [UInt8](repeating: 0,
count: Int(dataSize))
let colorSpace = CGColorSpaceCreateDeviceGray()
let context = CGContext(data: &pixelData,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: 1 * Int(size.width),
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.none.rawValue)!
context.draw(self,
in: CGRect(origin: .zero,
size: .init(width: size.width,
height: size.height)))
#if DEBUG
print("Grayscale time: \(CACurrentMediaTime() - startTime)")
#endif
return pixelData
}
}
#if os(macOS)
extension NSImage {
var cgImage: CGImage? {
return self.cgImage(forProposedRect: nil,
context: nil,
hints: nil)
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment