I need to create a base64 string representation of an NSImage cocoa object. What\'s the best way of handling this, apple documentation seems to be a little short on the subj
Here is a Swift 2 extension to convert NSImage into a base64 string:
private extension NSImage {
var base64String:String? {
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSDeviceRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0
) else {
print("Couldn't create bitmap representation")
return nil
}
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.setCurrentContext(NSGraphicsContext(bitmapImageRep: rep))
drawAtPoint(NSZeroPoint, fromRect: NSZeroRect, operation: .CompositeSourceOver, fraction: 1.0)
NSGraphicsContext.restoreGraphicsState()
guard let data = rep.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [NSImageCompressionFactor: 1.0]) else {
print("Couldn't create PNG")
return nil
}
return data.base64EncodedStringWithOptions([])
}
}