Objective-C: displaying an array of floats as an image

In a Cocoa application, I would like to display a 2d array of floats in NSImageView. To make the code as simple as possible, start by converting 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 remains blank):

 [theNSImageView setImage:[[NSImage alloc] initWithData:nsdata]]; 

Is this the right approach? First of all, do you need a CGContext? I was hoping to accomplish this using NSData.

I noted earlier Stack messages: 32-bit data , close, but vice versa>, it almost worked, but without NSData , there was color image data , but not much luck getting changes in work. Thanks for any suggestions.

+4
source share
2 answers

Ok, that worked. I tried NSBitmapImageRep before (thanks Tim), but the part I was missing was the correct conversion of the floating point data to an array of bytes. NSData does not do this and returns nil. Thus, the solution was not so much the need to create an NSImage float-by-float. In fact, you can also create a bitmapContext (using CGBitmapContextCreate (mentioned above in HotLicks)), and this also works once the floating point data has been presented correctly.

0
source

You can use NSBitmapImageRep to create an NSImage float-by-float.

Interestingly, one of its initializers has the longest method name in all Cocoa:

 - (id)initWithBitmapDataPlanes:(unsigned char **)planes pixelsWide:(NSInteger)width pixelsHigh:(NSInteger)height bitsPerSample:(NSInteger)bps samplesPerPixel:(NSInteger)spp hasAlpha:(BOOL)alpha isPlanar:(BOOL)isPlanar colorSpaceName:(NSString *)colorSpaceName bitmapFormat:(NSBitmapFormat)bitmapFormat bytesPerRow:(NSInteger)rowBytes bitsPerPixel:(NSInteger) 

This is well documented. Once you have built it by providing float arrays in planes , you can get NSImage to put in your view:

 NSImage *image = [[NSImage alloc] initWithCGImage:[bitmapImageRep CGImage] size:NSMakeSize(width,height)]; 

Or, a little cleaner

 NSImage *image = [[[NSImage alloc] init] autorelease]; [im addRepresentation:bitmapImageRep]; 

There is an initializer that simply uses the NSData container:

 + (id)imageRepWithData:(NSData *)bitmapData 

although it depends on your bitmapData containing one of the correct bitmap formats.

+2
source

Source: https://habr.com/ru/post/1394466/


All Articles