Search code examples
swiftpngcore-graphicscgcontext

CGContext always returns nil (Converting png to CGImage)


I am trying to load a png and convert it into a CGImage in Swift. I am not so experienced in Swift and I think I don't understand Core Graphics properly. Creating a CGContext always returns nil. Please help me. The Code looks like:

    let nsImage = NSImage(contentsOfFile: input)
    let cgImage = nsimage.cgImage(forProposedRect: nil, context: nil, hints: nil)
    var ratio: Float = 0.0
    let imageWidth = Float(cgImage!.width)
    let imageHeight = Float(cgImage!.height)
    let maxWidth: Float = Float(nsimage.size.width)
    let maxHeight: Float = Float(nsimage.size.height)
    if (imageWidth > imageHeight) {
        ratio = maxWidth / imageWidth
    } else {
        ratio = maxHeight / imageHeight
    }
    if ratio > 1 {
        ratio = 1
    }
    let width = imageWidth * ratio
    let height = imageHeight * ratio
    guard let colorSpace = cgImage!.colorSpace else { return nil }
    guard let cgContext = CGContext(data: nil, width: Int(width), height: Int(height),
                                    bitsPerComponent: cgImage!.bitsPerComponent, 
                                    bytesPerRow: cgImage!.bytesPerRow, 
                                    space: colorSpace, 
                                    bitmapInfo: cgImage!.alphaInfo.rawValue
                                    ) else { return nil }
    
    cgContext.interpolationQuality = .high
    cgContext.draw(cgImage!, in: CGRect(x: 0, y: 0, width: Int(width), height: Int(height)))
    let cgImage = cgContext.makeImage()

Solution

  • You can just open your png file like a simple UIImage. It has a default property called 'cgImage' that return an automatic conversion.

    import UIKit
    
    var image = UIImage(named : "test.png")
    var cgImage = image?.cgImage
    

    I hope this will solve your problem!