Davis Riedel
Davis Riedel

Reputation: 51

Objective-C: NSBitmapImageRep SetColor

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

Upvotes: 3

Views: 1164

Answers (1)

Atomix
Atomix

Reputation: 13842

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] ...

Upvotes: 1

Related Questions