Objective-C:将浮点数组显示为图像
在 Cocoa 应用程序中,我想在 NSImageView 中显示二维浮点数组。为了使代码尽可能简单,首先将数据从 float 转换为 NSData:
// dataArray: an Nx by Ny array of floats
NSMutableData *nsdata = [NSMutableData dataWithCapacity:0];
long numPixels = Nx*Ny;
for (int i = 0; i < numPixels; i++) {
[nsdata appendBytes:&dataArray[i] length:sizeof(float)];
}
现在尝试显示数据(显示留空):
[theNSImageView setImage:[[NSImage alloc] initWithData:nsdata]];
这是正确的方法吗?首先需要CGContext吗?我希望用 NSData 来完成这个任务。
我已经注意到早期的堆栈帖子: 32位数据,接近但相反,几乎有效,但没有 NSData,此处为彩色图像数据,但在这些工作上获得变化的运气并不好。感谢您的任何建议。
In a Cocoa App I would like to display a 2d array of floats in an NSImageView. To make the code as simple as possible, start off by converting the data from float to NSData:
// dataArray: an Nx by Ny array of floats
NSMutableData *nsdata = [NSMutableData dataWithCapacity:0];
long numPixels = Nx*Ny;
for (int i = 0; i < numPixels; i++) {
[nsdata appendBytes:&dataArray[i] length:sizeof(float)];
}
and now try to display the data (the display is left blank):
[theNSImageView setImage:[[NSImage alloc] initWithData:nsdata]];
Is this the correct approach? Is a CGContext needed first? I was hoping to accomplish this with NSData.
I have noted the earlier Stack posts: 32 bit data, close but in reverse, almost worked but no NSData, color image data here, but not much luck getting variations on these working. Thanks for any suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
NSBitmapImageRep
逐个构建NSImage
。有趣的是,它的初始化程序之一拥有 Cocoa 中最长的方法名称:
至少有详细记录。一旦你通过在
planes
中提供浮点数组来构建它,你就可以将NSImage
放入你的视图中:或者,稍微干净
一点有一个初始化程序,它只使用
NSData
容器:尽管这取决于您的
bitmapData
包含正确的位图格式之一。You can use an
NSBitmapImageRep
to build up anNSImage
float-by-float.Interestingly, one of its initialisers has the longest method name in all of Cocoa:
It's well documented at least. Once you've built it up by supplying float arrays in
planes
you can then get theNSImage
to put in your view:Or, slightly cleaner
There is an initialiser which just uses an
NSData
container:although that depends on your
bitmapData
containing one of the correct bitmap formats.好的,开始工作了。我之前曾尝试过 NSBitmapImageRep (感谢 Tim),但我缺少的部分是将浮点数据正确转换为字节数组。 NSData 不会这样做并返回 nil。因此,解决方案并不需要逐个浮点地构建 NSImage。事实上,我们可以类似地构建一个 bitmapContext(使用 CGBitmapContextCreate(上面 HotLicks 提到的)),并且一旦浮点数据被正确表示,它也可以工作。
Ok got it to work. I had tried the NSBitmapImageRep before (thanks Tim) but the part I was missing was in properly converting my floating point data to a byte array. NSData doesn't do that and returns nil. So the solution was not so much in needing to build up an NSImage float-by-float. In fact, one can similarly build up a bitmapContext (using CGBitmapContextCreate (mentioned by HotLicks above)) and that works too, once the floating point data has been represented properly.