0

fast code: from a "traditional" image buffer to NSImageView

Just a fast code lesson:

Assumptions:
gfx_data (uchar) –> our “traditional” RGB image buffer
IVFinalexture (NSImageView) –> where we want to view our image
bmp (NSBitmapImageRep) –> Temporal, to store the rgb buffer
img (NSImage) –> Temporal, to store the Bitmap

So the sequence (more or less) is:
uchar buffer –> NSBitmapImageRep –> NSImage –> NSImageView

 unsigned char *gfx_data;
 int gfx_width = 256;
 int gfx_heigth = 256;
 int gfx_samplespp = 3;

 gfx_data = malloc (gfx_width*gfx_heigth*gfx_samplespp);
 int i=0;
 int max = gfx_width*gfx_heigth*gfx_samplespp;
 for (i=0; i<(max);i+=3)
 {
 // Do your demoscene-fancy effect here
 int valor = sin((float)i*4.0/(float)(gfx_width*gfx_heigth))*255.0;
 if (valor<0) valor="valor*-1;
 gfx_data[i]= valor;
 }

 // Convert buffer to NSBitmapImageRep
 NSBitmapImageRep* bmp = [[NSBitmapImageRep alloc]initWithBitmapDataPlanes:&gfx_data
 pixelsWide: gfx_width
 pixelsHigh: gfx_heigth
 bitsPerSample: 8
 samplesPerPixel: gfx_samplespp
 hasAlpha: NO
 isPlanar: NO
 colorSpaceName: NSCalibratedRGBColorSpace
 bytesPerRow: (gfx_width*gfx_samplespp)
 bitsPerPixel: 24];

 // Store the NSBitmapImageRep in a NSImage structure
 NSImage *img = [NSImage alloc];
 [img addRepresentation:bmp];

 // Set the NSImage into the NSImageView (IVFinaltexture)
 if ([IVFinaltexture image]!=nil)
 [[IVFinaltexture image] release];
 [IVFinaltexture setImage:img];
 //free (gfx_data); // WTF! system crashes if I uncomment this!
 [bmp release];
 [img release]; 

I think that I’ve some problems releasing the data, but I think that you can make an idea of the process, I’m not describing how to write code, just explaining a process to display an image buffer in Cocoa (in my opinion, not properly documented).

————–

And… obviously… the result!!

.happy coding!!

Leave a Reply

Your email address will not be published. Required fields are marked *

spammer, go home! * Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.