Last active
July 3, 2022 11:55
-
-
Save KrisYu/abf3d03a76b781ffc2a26848d713b11e to your computer and use it in GitHub Desktop.
Save image to file on macOS using swift, answers found from SO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// plain write to image | |
@discardableResult func writeCGImage(_ image: CGImage, to destinationURL: URL) -> Bool { | |
guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else { return false } | |
CGImageDestinationAddImage(destination, image, nil) | |
return CGImageDestinationFinalize(destination) | |
} | |
// There's a panel, save image png | |
@IBAction func saveImage(sender: Any){ | |
let savePanel = NSSavePanel() | |
savePanel.canCreateDirectories = true | |
savePanel.showsTagField = false | |
savePanel.nameFieldStringValue = "screenshot.png" | |
savePanel.level = Int(CGWindowLevelForKey(.modalPanelWindow)) | |
savePanel.begin { (result) in | |
if result == NSFileHandlingPanelOKButton { | |
guard let url = savePanel.url else { return } | |
let bitmapRep = NSBitmapImageRep(cgImage: self.ikimageView.image().takeUnretainedValue()) | |
let data = bitmapRep.representation(using: .PNG, properties: [:]) | |
do { | |
try data?.write(to: url, options: .atomicWrite) | |
} catch { | |
print(error.localizedDescription) | |
} | |
} | |
} | |
} | |
// A more detailed, save image using IKImageView | |
@IBAction func saveImage(sender: AnyObject) { | |
let savePanel = NSSavePanel() | |
saveOptions = IKSaveOptions.init(imageProperties: [:], imageUTType: kUTTypePNG as String!) | |
saveOptions.addAccessoryView(to: savePanel) | |
savePanel.canSelectHiddenExtension = true | |
guard let window = self.view.window else { return } | |
// let fileName = window.representedURL?.lastPathComponent ?? "Untitled" | |
// savePanel.nameFieldStringValue = fileName | |
savePanel.beginSheetModal(for: window) { (result) in | |
if result == NSFileHandlingPanelOKButton { | |
self.savePanelDidEnd(sheet: savePanel,returnCode: result) | |
} | |
} | |
} | |
func savePanelDidEnd(sheet: NSSavePanel, returnCode: Int) { | |
if returnCode == NSModalResponseOK { | |
let newUTType = saveOptions.imageUTType | |
let iamge = imageView.image().takeUnretainedValue() | |
let url = sheet.url | |
if let dest = CGImageDestinationCreateWithURL(url! as CFURL, newUTType! as CFString, 1, nil) { | |
CGImageDestinationAddImage(dest, iamge, nil) | |
CGImageDestinationFinalize(dest) | |
} else { | |
print("save Image to Path - no image") | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment