title: Objective-C: Display an Array of Floats as an Image
body: <p>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:</p>
  
  <pre><code>// dataArray: an Nx by Ny array of floats
  NSMutableData *nsdata = [NSMutableData dataWithCapacity:0];
  long numPixels = Nx*Ny;
  for (int i = 0; i &lt; numPixels; i++) {
      [nsdata appendBytes:&amp;dataArray[i] length:sizeof(float)];
  }
  </code></pre>
  
  <p>and now try to display the data (the display is left blank):</p>
  
  <pre><code>[theNSImageView setImage:[[NSImage alloc] initWithData:nsdata]];
  </code></pre>
  
  <p>Is this the correct approach?  Is a CGContext needed first? I was hoping to accomplish this with NSData.</p>
  
  <p>I have noted the earlier Stack posts: <a href="https://stackoverflow.com/questions/5494535/32-bit-component-images-with-cgimagecreate-are-actually-only-8-bit-component">32 bit data</a>, <a href="https://stackoverflow.com/questions/3026110/convert-nsdata-to-primitive-variable-with-ieee-754-or-twos-complement">close but in reverse</a>, <a href="https://stackoverflow.com/questions/5458770/nsimage-from-a-1d-pixel-array">almost worked but no NSData</a>, <a href="https://stackoverflow.com/questions/7225985/how-to-create-image-from-unsigned-char">color image data here</a>, but not much luck getting variations on these working.  Thanks for any suggestions.</p>