在本地保存不同格式的NSImage

时间:2017-09-26 17:40:04

标签: swift macos

我需要允许用户将NSImage保存到本地文件。

因此,我使用此SO answer中的扩展程序可以将图像保存为PNG格式

extension NSBitmapImageRep {
    var png: Data? {
        return representation(using: .png, properties: [:])
    }
}
extension Data {
    var bitmap: NSBitmapImageRep? {
        return NSBitmapImageRep(data: self)
    }
}
extension NSImage {
    var png: Data? {
        return tiffRepresentation?.bitmap?.png

    }
    func savePNG(to url: URL) -> Bool {
        do {
            try png?.write(to: url)
            return true
        } catch {
            print(error)
            return false
        }

    }
}

是否有更简单的方法以{JPEG,TIFF,BMP等格式保存NSImage

2 个答案:

答案 0 :(得分:1)

您可以将Expires转换为NSImage,然后使用NSBitmapImageRep方法获取BMP,GIF,JPEG,JPEG2000,PNG或TIFF,但它可以获得&#39有点痛苦;您必须创建一个空representation(using:),将其设置为当前图形上下文,并将NSBitmapImageRep绘制到其中(有关详细信息,请参阅this answer)。

如果您需要macOS 10.13,NSImage上有一些方便的方法,在我看来,更容易使用,并且可以将图像转换为TIFF,JPEG或PNG(没有BMP,GIF ,或JPEG2000虽然;还有,有一种转换为HEIF的方法,截至撰写本文时,它似乎只是iOS):

CIContext

答案 1 :(得分:1)

您可以创建自定义方法,以允许您指定任何图像类型以及要保存NSImage的目录。您还可以将目标目录的默认值设置为当前目录,因此如果您不通过目录URL,它将保存到当前目录:

extension NSImage {
    func save(as fileName: String, fileType: NSBitmapImageRep.FileType = .jpeg, at directory: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)) -> Bool {
        guard let tiffRepresentation = tiffRepresentation, directory.isDirectory, !fileName.isEmpty else { return false }
        do {
            try NSBitmapImageRep(data: tiffRepresentation)?
                .representation(using: fileType, properties: [:])?
                .write(to: directory.appendingPathComponent(fileName).appendingPathExtension(fileType.pathExtension))
            return true
        } catch {
            print(error)
            return false
        }
    }
}

您还需要确保传递给您的方法的网址是目录网址。您可以使用URL resourceValues方法获取url isDirectoryKey值并检查它是否为true:

extension URL {
    var isDirectory: Bool {
       return (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
    }
}

您还可以扩展NSBitmapImageRep.FileType以提供关联的文件路径扩展名:

extension NSBitmapImageRep.FileType {
    var pathExtension: String {
        switch self {
        case .bmp:
            return "bmp"
        case .gif:
            return "gif"
        case .jpeg:
            return "jpg"
        case .jpeg2000:
            return "jp2"
        case .png:
            return "png"
        case .tiff:
            return "tif"
        }
    }
}

游乐场测试:

let desktopDirectory = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
// lets change the current directory to the desktop directory
FileManager.default.changeCurrentDirectoryPath(desktopDirectory.path)

// get your nsimage
let picture  = NSImage(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!)!

// this will save to the current directory
if picture.save(as: "profile") {
    print("file saved as profile.jpg which is the default type")
}
if picture.save(as: "profile", fileType: .png) {
    print("file saved as profile.png")
}
if picture.save(as: "profile", fileType: .tiff) {
    print("file saved as profile.tif")
}
if picture.save(as: "profile", fileType: .gif) {
    print("file saved as profile.gif")
}
if picture.save(as: "profile", fileType: .jpeg2000) {
    print("file saved as profile.jp2")
}

// you can also chose a choose another directory without the need to change the current directory
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
if picture.save(as: "profile", at: url) {
    print("file saved as profile.jpg at documentDirectory")
}