I'm trying to create and save a .png
from raw pixel data. I create an array of UInt8
where each number is a rgba value, kinda like this: [r, g, b, a, r, g, b, a...]
. I can use this array to create a CGImage
just fine. I can even use the CGImage
to create an NSImage
. The NSImage
displays how I expect it to display when its loaded into an NSImageView
.
What I want to do is to save an NSImage
to disk. I've tried calling TIFFRepresentation
on the NSImage
and saving the NSData
to "~/Desktop", but no file is saved. Any thoughts?
var pixels = [UInt8]()
for wPixel in 0...width {
for hPixel in 0...height {
pixels.append(0xff)
pixels.append(0xaa)
pixels.append(UInt8(wPixel % 200))
pixels.append(0x00)
}
}
let image = createImage(100, height:100, pixels: pixels)
let nsImage = NSImage(CGImage: image, size: CGSize(width: 100, height: 100))
NSBitmapImageRep(data: nsImage.TIFFRepresentation!)!.representationUsingType(.NSPNGFileType, properties: [:])!.writeToFile("~/Desktop/image.png", atomically: true)
func createImage(width: Int, height: Int, pixels:Array<UInt8>) -> CGImage{
let componentsPerPixel: Int = 4; // rgba
let provider: CGDataProviderRef = CGDataProviderCreateWithData(nil,
pixels,
width * height * componentsPerPixel,
nil)!;
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue)
let bitsPerComponent = 8
let bitsPerPixel = 32
let bytesPerRow = (bitsPerComponent * width) ;
let cgImage = CGImageCreate(
width,
height,
bitsPerComponent,
bitsPerPixel,
bytesPerRow,
rgbColorSpace,
bitmapInfo,
provider,
nil,
true,
.RenderingIntentDefault
)
print(cgImage.debugDescription)
return cgImage!;
}