将NSImage本地保存为不同格式 [英] Saving NSImage in Different Formats Locally

查看:262
本文介绍了将NSImage本地保存为不同格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to allow the user to save an NSImage to a local file.

所以我正在使用SO answer 中的那些扩展名以将图片保存为PNG格式

So I am using those extensions from this SO answer to can save the image in PNG Format

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
        }

    }
}

是否有更简便的方法将NSImage保存为JPEG,TIFF,BMP等不同格式

Is there an easier way to save NSImage in different formats like JPEG,TIFF,BMP etc

推荐答案

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

You can create a custom method to allow you to specify any image type and also the directory where you would like to save your NSImage. You can also set a default value to the destination directory as the current directory, so if you don't pass the directory url it will save to the current one:

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是目录url.您可以使用URL resourceValues方法获取url isDirectoryKey值并检查其是否为真:


You will need also to make sure the url passed to your method is a directory url. You can use URL resourceValues method to get the url isDirectoryKey value and check if it is true:

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


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


You can also extend NSBitmapImageRep.FileType to provide the associated file path extension:

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


游乐场测试:


Playground Testing:

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

这篇关于将NSImage本地保存为不同格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆