在swift中获取NSImage的PNG表示

时间:2015-01-30 05:49:00

标签: swift

嘿,我在获取NSImage对象的PNG表示时遇到了一些麻烦。

这就是我正在做的事情:

var imgData: NSData! = coverImgView.image!.TIFFRepresentation!
var bitmap: NSBitmapImageRep! = NSBitmapImageRep(data: imgData!)
var pngCoverImage = bitmap!.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: nil)

coverImgView是一个NSImageView对象

然而,我甚至无法以某种方式编译它。

它说:键入' [NSObject:AnyObject]'不符合协议' NilLiteralConvertible' (我在上面发布的代码的第三行,参数"属性:nil")

我尝试做类似功能的事情" PNGRepresentationOfImage"这里https://gist.github.com/mtabini/1178403

有什么想法吗?

非常感谢〜

1 个答案:

答案 0 :(得分:10)

文档说:

func representationUsingType(_ storageType: NSBitmapImageFileType,
              properties properties: [NSObject : AnyObject]) -> NSData?

所以它期望一本字典,而不是一个零值。提供一个像这样的空字典:

var pngCoverImage = bitmap!.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])

仅当指定了Optional时(即[NSObject : AnyObject]?)可以传递nil值。