从像素阵列问题中获取NSImage(Swift)

时间:2016-07-26 12:47:32

标签: arrays swift byte pixel cgimage

L.E:我发现了这个问题,现在它已经崩溃了,但是现在(新问题)它没有画出它应该的图像......它已经损坏......

我有一个像素数组,我需要变成一个CGImage,然后变成一个NSImage。我试过在ios上使用这个版本的代码来获取一个UIImage,我得到一个我无法处理的错误: CGImageCreate:无效的图像位/像素或字节/行。 致命错误:在解开可选值时意外发现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)
}

1 个答案:

答案 0 :(得分:2)

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

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

请参阅代码中的注释。