I am looking for a routine to convert a rgb tiff into a greyscale tiff. I am currently using the following, but it takes about 4-5 seconds on a US letter sized page (too slow!). I had thought to use tiff2bw (part of the libtiff tools), but I get an error when using an image that I saved out using TIFFRepresentation (about bad samplesPerPixel)
Any help would be greatly appriciated.
Code:
- (NSImage *)filterImage:(NSImage *)srcImage
{
NSBitmapImageRep *TIFFRep = [NSBitmapImageRep imageRepWithData:[srcImage TIFFRepresentation]];
int samplesPerPixel = [TIFFRep samplesPerPixel];
int bytesPerSample = ([TIFFRep bitsPerPixel]/8)/samplesPerPixel;
int totalBytes = [TIFFRep pixelsHigh]*[TIFFRep pixelsWide]*samplesPerPixel*bytesPerSample;
grayRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:[TIFFRep pixelsWide]
pixelsHigh:[TIFFRep pixelsHigh]
bitsPerSample:8
samplesPerPixel:1
hasAlpha:NO
isPlanar:NO
colorSpaceName:NSCalibratedWhiteColorSpace
bytesPerRow:0
bitsPerPixel:0];
[grayRep setSize:[TIFFRep size]];
unsigned char *TIFFBitmapPointer = [TIFFRep bitmapData];
unsigned char *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];
NSImage *grayImage = [[NSImage alloc] initWithData:[grayRep TIFFRepresentation]];
return grayImage;
}