faqts : Computers : Programming : Application Frameworks : Macintosh : Cocoa

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 6 people (83%) answered Yes
Recently 5 of 6 people (83%) answered Yes

Entry

How can i access (get/set) the value of single pixels inside an NSImage?

Aug 20th, 2002 04:43
henriette delchevry, Martin Bauer,


Hello

an NSImage contains one or more NSImageRep's, each of which can be
bitmap or vector. This piece of code shows how to acces a
NSBitmapImageRep of a give pixel depth and format, and set a given pixel
of it to yellow:


  int x,y; // pixel coordinates
  NSImage *img; // the image

  NSArray *reps=[img representations];
  NSEnumerator *enumerator = [reps objectEnumerator];
  id obj;
  NSBitmapImageRep *bir;
  
  // cycle through the image reps until we find a suitable one
  while ((obj = [enumerator nextObject])) {
    bir=nil;
    if([obj isKindOfClass: [NSBitmapImageRep class]]) {
      bir=(NSBitmapImageRep *)obj;
      // we select a 32 bpp RGB image with 8 bit per sample
      if([bir bitsPerPixel]==32 && 
          ![bir isPlanar] && 
          [bir samplesPerPixel]==3 && 
          [bir colorSpaceName]==NSCalibratedRGBColorSpace)
        break;
    }
  }
  
  if(bir) {
    struct {
      unsigned char r,g,b,a;
    } *pixels=(void*) [bir bitmapData];
    unsigned int ppl=[bir bytesPerRow]/4; 
    // assuming rows are aligned...
    
    // set the pixel pointed by x, y to yellow
    pixels[x+ppl*y].r=0xff;
    pixels[x+ppl*y].g=0xff;
    pixels[x+ppl*y].b=0;
  } else {
    // error: no suitable image rep
  }