将NSImage保存为Swift中的png

时间:2016-07-13 20:03:01

标签: swift macos cgimage

我尝试从原始像素数据创建并保存.png。我创建了一个UInt8数组,其中每个数字都是一个rgba值,有点像:[r, g, b, a, r, g, b, a...]。我可以使用这个数组创建一个CGImage就好了。我甚至可以使用CGImage创建NSImageNSImage显示加载到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!;
}

0 个答案:

没有答案