NSPNGFileType -在Swift中找不到?

uinbv5nw  于 9个月前  发布在  Swift
关注(0)|答案(2)|浏览(79)

今天,我发现了一件奇怪的事情:
我想用Swift写这段代码:

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

字符串
在Swift中,它看起来像这样:

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


问题是编译器说:“使用未解析的标识符'NSPNGFileType'”。有人知道为什么吗?
谢谢,对不起我的英语!

e1xvtsh3

e1xvtsh31#

将NSImage转换为tiff,然后在Swift 5+中使用.png获取数据。
获取图像数据:

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

字符串
如果你想保存图像,你可以这样写:
对于Mac应用,您可能需要添加“功能”来保存文件。在应用沙盒中为“下载文件夹”启用读/写。

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")
}

bwleehnv

bwleehnv2#

在Swift 3中,这已更改为简单的.PNG或完整版本NSBitmapImageFileType.PNGdocs)。

相关问题