C-Viorel
C-Viorel

Reputation: 1866

NSPNGFileType - not found in Swift?

Today, I found something strange :

I wanted to write this code in swift :

    NSData *data = [myImage representationUsingType: NSPNGFileType properties: nil];

In swift it's look like this:

var data: NSData = imageToSave?.representationUsingType( NSPNGFileType ,
            properties: nil)

The problem is that the compiler say : " Use of unresolved identifier 'NSPNGFileType'". Does anyone have any idea why ?

Thanks, and sorry for my english !

Upvotes: 5

Views: 1721

Answers (2)

Antonio
Antonio

Reputation: 72760

Convert the NSImage to tiff and then get the data using .png in Swift 5+.

To get the image data:

if let tiffRepresentation = icon.tiffRepresentation,
   let imageRep = NSBitmapImageRep(data: tiffRepresentation) {
    let data = imageRep.representation(using: .png, properties: [:])
    
   // Use the data
} 

If you want to save the image, you can write something like this:

For Mac apps, you may need to add "Capabilities" to save the file. Enable Read/Write for "Downloads Folder" in the App Sandbox.

let downloads = FileManager.default.homeDirectoryForCurrentUser.appending(component: "Downloads")
let path = downloads.appending(components: "image.png")
if let tiffRepresentation = icon.tiffRepresentation,
   let imageRep = NSBitmapImageRep(data: tiffRepresentation) {
    let data = imageRep.representation(using: .png, properties: [:])
    do {
        try data?.write(to: path, options: .atomic)
    } catch {
        print("Error saving: path\(path) error: \(error)")
    }
} else {
    print("Invalid image")
}

Upvotes: 7

Maccesch
Maccesch

Reputation: 2128

In Swift 3 this has changed to simply .PNG or as the full version NSBitmapImageFileType.PNG (docs).

Upvotes: 4

Related Questions