Skip to content

Instantly share code, notes, and snippets.

@eliakorkmaz
Forked from KrisYu/saveImage.swift
Created May 30, 2020 10:12
Show Gist options
  • Save eliakorkmaz/1849f79d27cf6b846d6038e157404266 to your computer and use it in GitHub Desktop.
Save eliakorkmaz/1849f79d27cf6b846d6038e157404266 to your computer and use it in GitHub Desktop.
Save image to file on macOS using swift, answers found from SO
// 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