如何将 NSData 转换为数据

How to cast NSData to Data

我创建了 UInt8 数组

var pixels: [UInt8] = []

由 alpha、红色、绿色和蓝色组件填充,需要从他的数组创建 NSImage。我写了下面的代码

let imageData = NSData(bytes: pixels, length: 1000)
Swift.print(imageData)
newImage = NSImage(data: imageData as Data)!

其中 print 命令打印我的字节,例如 ff0493f8 ff455772 ffa281ed ff9c14d7 ff6eb302... 但是创建 newImage 失败并出现错误 "fatal error: unexpectedly found nil while unwrapping an Optional value"。 我做错了什么? 谢谢

你有一些问题。

  1. 为什么要使用 NSData?只需使用 Data.
  2. 您的错误是 imageData 实际上并不代表有效图像,因此 NSImagenil 但您试图强制展开它。

尝试这样的事情:

let imageData = Data(bytes: pixels)
Swift.print(imageData)
if let newImage = NSImage(data: imageData) {
    // Do something with the image
} else {
    // oops - can't create the image
}