2016-07-26 78 views
1

LE:我發現了這個問題,現在它不會崩潰了,但現在(新問題)它不會像應該那樣繪製圖像。 ...從像素陣列問題獲取NSImage(Swift)

我有一個像素數組,我需要變成一個CGImage,然後進入NSImage。我試過這個版本的代碼用於獲取iUIImage的ios,我得到一個我無法處理的錯誤:CGImageCreate:無效的圖像位/像素或字節/行。 致命錯誤:意外地發現零,而解包一個可選值

任何想法,任何幫助將誠實地讚賞!謝謝!我會在這裏讓代碼:

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

請注意,這不是重複的,因爲我需要在osx上開發,而不是ios,因爲我沒有使用RGB結構。 –

+0

請注意,答案中的代碼首先創建一個CGImage,並且應該可以在OS X和iOS上使用。您可以用一組像素數據替換RGB結構數組。 –

+0

我試過這種方法,不幸的是它崩潰了... –

回答

1

你的新的代碼比舊的一個多個故障,所以一些修正:

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

參見代碼中的註釋。