import AppKit

extension NSImage {

    func writePng(to url: URL) -> Bool {
        // Get CGImage from NSImage
        guard let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
            return false
        }

        // Create a bitmap representation
        let bitmapRep = NSBitmapImageRep(cgImage: cgImage)
        bitmapRep.size = self.size  // Preserve image size

        // Convert to PNG data
        guard let pngData = bitmapRep.representation(using: .png, properties: [:]) else {
            return false
        }

        do {
            try pngData.write(to: url)
            return true
        } catch {
            print("Error writing PNG:", error)
            return false
        }
    }
}
