2007年10月24日水曜日

NSImage:特定色だけ透明にするコード

ぜんぜん美しくないけどまぁうごいたよ…
(NSBitmapImageRepからNSImageをつくる方法が特に.)
#透明にする方法等,もっといい方法があれば教えていただければ幸いです.

#10/29更新(アルファーチャネルを自分で追加.カラースペースをRGBAに逐次変換して作業するように修正)NSBitmapImageRepからNSImageを作るのはこれが正解だな.

NSColor *tColor= [NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0];
float tr= [tColor redComponent];
float tg= [tColor greenComponent];
float tb= [tColor blueComponent];
NSColor *sColor= [NSColor colorWithCalibratedRed:tr green:tg blue:tb alpha:0.0];

NSImage *inImage= [[NSImage alloc] initWithContentsOfFile:@"/path/to/file"];
NSSize size= [inImage size];
int w= [[NSNumber numberWithFloat:size.width] intValue];
int h= [[NSNumber numberWithFloat:size.height] intValue];
//
NSBitmapImageRep *inBitImage= [NSBitmapImageRep imageRepWithData:[inImage TIFFRepresentation]];
unsigned char *oa= malloc(sizeof(unsigned char) * w * h * 4);
NSBitmapImageRep *outBitImage=
[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:oa
pixelsWide:w
pixelsHigh:h
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:@"NSCalibratedRGBColorSpace"
bitmapFormat:NSAlphaFirstBitmapFormat
bytesPerRow:(4 * w)
bitsPerPixel:(4 * 8)];
int i, j;
for (i= 0; i<h; i++) {
for(j= 0; j<w; j++) {
NSColor *color= [inBitImage colorAtX:j y:i];
color= [color colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
float r= [color redComponent];
float g= [color greenComponent];
float b= [color blueComponent];
if (r==tr && g==tg && b==tb) {
[outBitImage setColor:sColor atX:j y:i];
}
else {
[outBitImage setColor:color atX:j y:i];
}
}
}
NSImage *outImage= [[NSImage alloc] initWithData:[outBitImage TIFFRepresentation]];

0 件のコメント: