I am having some issues. Ever since upgrading to 10.4 (and also upgrading my copy of Xcode), the following code just gives me a jar-bled image. The code used to work fine. It would take an image that was 4 samplesPerPixel, and convert it to an image that was 1 samplesPerPixel (effectively taking a color image and converting it to black and white). I don't know if this is now easier to do with Core Image (I haven't looked at that stuff just yet), and if so I could use that (the code only needs to work on 10.4 and later systems, as the old version of my app works fine under 10.3 and earlier).
Here is my current code. If anyone spots a mistake, or a change Apple has made recently, or has suggestions on how to better do this, please let me know:
Code:
- (NSImage *)filterImage:(NSImage *)srcImage originalSize:(NSSize)originalSize
{NSAutoreleasePool *imagePool = [[NSAutoreleasePool alloc] init];
NSBitmapImageRep *TIFFRep = [NSBitmapImageRep imageRepWithData:[srcImage TIFFRepresentationUsingCompression:NSTIFFCompressionLZW factor:0.0]];
NSImage *grayImage;
NSBitmapImageRep *grayRep;
int samplesPerPixel = [TIFFRep samplesPerPixel];
int bytesPerSample = ([TIFFRep bitsPerPixel]/8)/samplesPerPixel;
int totalBytes = [TIFFRep pixelsHigh]*[TIFFRep pixelsWide]*samplesPerPixel*bytesPerSample;
unsigned char *TIFFBitmapPointer = [TIFFRep bitmapData];
unsigned char *grayBitmapPointer;
grayRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULLpixelsWide:[TIFFRep pixelsWide]
pixelsHigh:[TIFFRep pixelsHigh]
bitsPerSample:8
samplesPerPixel:1
hasAlpha:NO
isPlanar:NO
colorSpaceName:NSCalibratedWhiteColorSpace
bytesPerRow:0
bitsPerPixel:0];
[grayRep setSize:[TIFFRep size]];
grayBitmapPointer = [grayRep bitmapData];
if((bytesPerSample==1)&&(samplesPerPixel>2))
{int o = 0;
int i = 0;
int background = 255;
for (i=0; i<totalBytes; i+=samplesPerPixel)
{int R = (int)*(TIFFBitmapPointer+i);
int G = (int)*(TIFFBitmapPointer+i+1);
int B = (int)*(TIFFBitmapPointer+i+2);
int grayValue = (int)((R+G+B)/3);
if (samplesPerPixel==4)
{int alpha = (int)*(TIFFBitmapPointer+i+3); // this is the alpha value
grayValue = (int) ( (grayValue*alpha + background*(255-alpha)) / 255);
}
*(grayBitmapPointer+o) = grayValue;
o++;
}
} else NSLog(@"Bytes per sample != 1 or less than 3 samples per pixel");;
[grayRep setSize:originalSize];
grayImage = [[NSImage alloc] initWithData:[grayRep TIFFRepresentationUsingCompression:NSTIFFCompressionLZW factor:0.0]];
[grayRep release];
[imagePool release];
return [grayImage autorelease];
}
Thanks,
Ben