Saving NSImage in Different Formats Locally

后端 未结 2 1208
梦如初夏
梦如初夏 2021-01-07 14:39

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

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

2条回答
  •  無奈伤痛
    2021-01-07 15:08

    You can get a BMP, GIF, JPEG, JPEG2000, PNG, or a TIFF by converting your NSImage to a NSBitmapImageRep and then using its representation(using:) method, but it's a bit of a pain; you have to create an empty NSBitmapImageRep, set it as the current graphics context, and draw your NSImage into it (see this answer for details).

    If you can require macOS 10.13, there are some handy methods on CIContext that are, in my opinion, easier to use, and which can convert an image to TIFF, JPEG, or PNG (no BMP, GIF, or JPEG2000 though; also, there's a method to convert to HEIF that appears to be iOS only as of the time of this writing):

    func getPNGData(image: NSImage) -> NSData? {
        if let ci = image.cgImage(forProposedRect: nil, context: nil, hints: nil).map({ CIImage(cgImage: $0) }),
            let png = CIContext().pngRepresentation(of: ci, format: kCIFormatRGBAf, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!) {
            // I'm colorblind, so it's very possible that the constants above
            // were poorly chosen. Choose whatever makes your colors look right
            return png
        } else {
            return nil
        }
    }
    

提交回复
热议问题