3

I'm trying to read an NSImage into an NSBitmapImageRep, for changing the color of some pixels. The Program should read the Color-Value of each pixel, and check if its equal to a color which is selected by a colorwell. I've got an ImageView named "MainImageView" and a ColorWell named "MainColor". That's my code:

- (IBAction)ScanImg:(id)sender {

NSBitmapImageRep *ImgRep = [[NSBitmapImageRep alloc]initWithData: MainImageView.image.TIFFRepresentation];

for (int pixelx = 0; pixelx < ImgRep.pixelsWide; pixelx ++) {
    for (int pixely = 0; pixely < ImgRep.pixelsHigh;pixely ++){
        if ([ImgRep colorAtX:pixelx y:pixely] == MainColor.color) {
            [ImgRep setColor: [NSColor whiteColor] atX:pixelx y:pixely];
        } else{
            [ImgRep setColor: [NSColor blackColor] atX:pixelx y:pixely];
        }
    }
}

struct CGImage *CG = [ImgRep CGImage];
NSImage *Image = [[NSImage alloc] initWithCGImage:CG size:ImgRep.size];
MainImageView.image = Image;

}

But the Code changes nothing on the picture! What's the problem? Or is there another way, to change the pixel's Color?

Thank you for your help! DaRi

  • I cant imagine that `[ImgRep colorAtX:pixelx y:pixely] == MainColor.color` is doing what you think... that is comparing `NSColor` object addresses. – Brad Allred Feb 12 '15 at 21:41
  • first check if `ImgRep` is `nil` and has dimensions. learn to use a debugger and put breakpoints to see if it is even getting to the `setColor` operations. – Brad Allred Feb 12 '15 at 21:42
  • And even after replacing the buggy color comparison it will not work because an existing NSBitmapImageRep cannot be changed. From the docs: **The object treats the image data in the buffers as immutable and will not attempt to alter it.** You have to create a new image. – Heinrich Giesen Feb 13 '15 at 10:24
  • Yes the Code comes to the point where it should set the pixel's color. But I have modified the comparison nethertheless, with the help of this Theard: http://stackoverflow.com/questions/1592995/comparing-colors-in-objective-c -- But it's still not working. @HeinrichGiesen Don't understand, why it's not working. Why is there a set color-method if you can't change anything on the image?? – Davis Riedel Feb 14 '15 at 08:37

1 Answers1

1

I have the same issue. A workaround I found is to use the -setPixel method, although this feels a bit clumsy:

NSUInteger pix[4]; pix[0] = 0; pix[1] = 0; pix[2] = 0; pix[3] = 255; //black
[ImgRep setPixel:pix atX:x y:y];

Note: The pixel data must be arranged according to the color space you are using, in this example 0,0,0,255 is black in RGBA color space.

But in the end, thats still better than copying and modifying the underlying (unsigned char*) data that is returned by [ImgRep bitmapData] ...

Atomix
  • 13,427
  • 9
  • 38
  • 46