Swift NSImage到CGImage

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift NSImage到CGImage相关的知识,希望对你有一定的参考价值。

如何在Swift中将NSImage转换为CGImage?在Objective-C中,我这样做:

- (CGImageRef)CGImage {
    NSData *imageData = self.TIFFRepresentation;
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
    CGImageRef maskRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);
    return maskRef;
}

现在我尝试了:

extension NSImage {
    var CGImage: CGImageRef {
    get {
        let imageData = self.TIFFRepresentation
        let source = CGImageSourceCreateWithData(imageData as CFDataRef, nil)
        let maskRef = CGImageSourceCreateImageAtIndex(source, UInt(0), nil)
        return maskRef;
    }
    }
}

我无法编译,我收到错误:Could not find an overload for 'init' that accepts the supplied arguments'let maskRef ...

答案

这是我用来将NSImage转换为CGImage的方法:

let image = NSImage(named:"image")
if let image = image {
    var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
    var imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)
}
另一答案

啊,我找到了解决方案。这是因为在Swift中你只有一个非托管对象(我只是不明白,这意味着什么)。但是这个代码现在有效:

extension NSImage {
    var CGImage: CGImageRef {
    get {
        let imageData = self.TIFFRepresentation
        let source = CGImageSourceCreateWithData(imageData as CFDataRef, nil).takeUnretainedValue()
        let maskRef = CGImageSourceCreateImageAtIndex(source, UInt(0), nil)
        return maskRef.takeUnretainedValue();
    }
    }
}
另一答案

Swift 3和4版本代码: -

if let image = NSImage(named: "Icon"){
    let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)
}
另一答案

对于Swift 4.0,XCode 9.2:

extension NSImage {
    @objc var CGImage: CGImage? {
       get {
            guard let imageData = self.tiffRepresentation else { return nil }
            guard let sourceData = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil }
            return CGImageSourceCreateImageAtIndex(sourceData, 0, nil)
       }
    }
}

以上是关于Swift NSImage到CGImage的主要内容,如果未能解决你的问题,请参考以下文章

从CGImage获取像素格式

如何在 Swift 中将 CGImage 保存到数据中?

如何在 swift 中从 nsimage 创建灰度图像?

在 NSImage 和 Leptonica Pix 之间转换

如何通过 Swift 使用 NSSlider 为 NSImage 类调整亮度?

让 CGImage 适应 Swift