CGContext 始终 returns nil(将 png 转换为 CGImage)

CGContext always returns nil (Converting png to CGImage)

我正在尝试加载 png 并将其转换为 Swift 中的 CGImage。 我在 Swift 方面经验不足,我想我没有正确理解 Core Graphics。 创建 CGContext 总是 returns nil。 请帮我。 代码如下所示:

    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()

您可以像打开简单的 UIImage 一样打开 png 文件。它有一个默认的 属性 调用 'cgImage',return 一个自动转换。

import UIKit

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

希望这能解决您的问题!