从像素数组问题中获取 NSImage (Swift)

Obtain NSImage from Pixel Array Problems (Swift)

L.E : 我找到了问题,现在它不再崩溃了,但是现在(新问题)它没有按应有的方式绘制图像。它已损坏...

我有一个像素数组,我需要将其转换为 CGImage,然后再转换为 NSImage。我已经尝试过在 ios 上使用此版本的代码来获取 aUIImage,但出现无法处理的错误:CGImageCreate:图像无效 bits/pixel 或 bytes/row。 致命错误:在展开可选值

时意外发现 nil

任何想法,任何帮助将不胜感激!谢谢!我会把代码放在这里:

 func imageFromPixels(image : CGImage, size:NSSize,pixels: UnsafeMutablePointer<UInt8>, width: Int, height: Int)-> NSImage {
    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
   let bitsPerComponent = CGImageGetBitsPerComponent(image)
    let bitsPerPixel = CGImageGetBitsPerPixel(image)
    let bytesPerRow = CGImageGetBytesPerRow(image)
    var data = pixels
    let providerRef = CGDataProviderCreateWithCFData(
        NSData(bytes: &data, length: height * width  * sizeof(UInt8))
    )

    let cgim = CGImageCreate(
        width,
        height,
        bitsPerComponent,
        bitsPerPixel,
        bitsPerRow,
        rgbColorSpace,
        bitmapInfo,
        providerRef,
        nil,
        true,
        .RenderingIntentDefault
    )
    return NSImage(CGImage: cgim!, size: size)
}

您的新代码比旧代码有更多错误,因此进行一些修复:

func imageFromPixels(size: NSSize, pixels: UnsafePointer<UInt8>, width: Int, height: Int)-> NSImage { //No need to pass another CGImage
    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
    let bitsPerComponent = 8 //number of bits in UInt8
    let bitsPerPixel = 4 * bitsPerComponent //ARGB uses 4 components
    let bytesPerRow = bitsPerPixel * width / 8 // bitsPerRow / 8 (in some cases, you need some paddings)
    let providerRef = CGDataProviderCreateWithCFData(
        NSData(bytes: pixels, length: height * bytesPerRow) //Do not put `&` as pixels is already an `UnsafePointer`
    )

    let cgim = CGImageCreate(
        width,
        height,
        bitsPerComponent,
        bitsPerPixel,
        bytesPerRow, //->not bits
        rgbColorSpace,
        bitmapInfo,
        providerRef,
        nil,
        true,
        .RenderingIntentDefault
    )
    return NSImage(CGImage: cgim!, size: size)
}

查看代码中的注释。