Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift NSImage to CGImage

How can I convert a NSImage to CGImage in Swift? In Objective-C I did it like this:

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

Now I tried with:

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

I can't compile, I'm getting the error: Could not find an overload for 'init' that accepts the supplied arguments' at the line let maskRef ...

like image 940
Lupurus Avatar asked Jul 06 '14 12:07

Lupurus


Video Answer


3 Answers

Here's what I'm using to convert NSImage to CGImage:

let image = NSImage(named:"image")
if let image = image {
    var imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
}
like image 108
az_ Avatar answered Oct 14 '22 01:10

az_


Swift 5 code :-

if let image = NSImage(named: "Icon"){
    let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)
}
like image 16
Jay Mehta Avatar answered Oct 14 '22 01:10

Jay Mehta


Ah, I found the solution. It's because in Swift you only the an unmanaged object (I just did not really understand, what this means). But this code now works:

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();
    }
    }
}
like image 9
Lupurus Avatar answered Oct 13 '22 23:10

Lupurus