NSImage to Base64

后端 未结 6 859
春和景丽
春和景丽 2021-01-18 06:51

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

6条回答
  •  星月不相逢
    2021-01-18 07:37

    Swift 4

    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: .calibratedRGB,
                bytesPerRow: 0,
                bitsPerPixel: 0
                ) else {
                    print("Couldn't create bitmap representation")
                    return nil
            }
    
            NSGraphicsContext.saveGraphicsState()
            NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
            draw(at: NSZeroPoint, from: NSZeroRect, operation: .sourceOver, fraction: 1.0)
            NSGraphicsContext.restoreGraphicsState()
    
            guard let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: 1.0]) else {
                print("Couldn't create PNG")
                return nil
            }
    
            // With prefix
            // return "data:image/png;base64,\(data.base64EncodedString(options: []))" 
            // Without prefix
            return data.base64EncodedString(options: []))
        }
    }
    

提交回复
热议问题