我尝试从原始像素数据创建并保存.png
。我创建了一个UInt8
数组,其中每个数字都是一个rgba值,有点像:[r, g, b, a, r, g, b, a...]
。我可以使用这个数组创建一个CGImage
就好了。我甚至可以使用CGImage
创建NSImage
。 NSImage
显示加载到NSImageView
时我希望它显示的方式。
我想要做的是将NSImage
保存到磁盘。我尝试在TIFFRepresentation
上拨打NSImage
并将NSData
保存到"〜/ Desktop"但是没有保存文件。有什么想法吗?
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!;
}