如何将NSImage转换为NSBitmapImageRep?我有代码:NSImage到NSBitmapImageRep
- (NSBitmapImageRep *)bitmapImageRepresentation
{
NSBitmapImageRep *ret = (NSBitmapImageRep *)[self representations];
if(![ret isKindOfClass:[NSBitmapImageRep class]])
{
ret = nil;
for(NSBitmapImageRep *rep in [self representations])
if([rep isKindOfClass:[NSBitmapImageRep class]])
{
ret = rep;
break;
}
}
if(ret == nil)
{
NSSize size = [self size];
size_t width = size.width;
size_t height = size.height;
size_t bitsPerComp = 32;
size_t bytesPerPixel = (bitsPerComp/CHAR_BIT) * 4;
size_t bytesPerRow = bytesPerPixel * width;
size_t totalBytes = height * bytesPerRow;
NSMutableData *data = [NSMutableData dataWithBytesNoCopy:calloc(totalBytes, 1) length:totalBytes freeWhenDone:YES];
CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef ctx = CGBitmapContextCreate([data mutableBytes], width, height, bitsPerComp, bytesPerRow, CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGBitmapFloatComponents | kCGImageAlphaPremultipliedLast);
if(ctx != NULL)
{
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:[self isFlipped]]];
[self drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
[NSGraphicsContext restoreGraphicsState];
CGImageRef img = CGBitmapContextCreateImage(ctx);
ret = [[NSBitmapImageRep alloc] initWithCGImage:img];
[self addRepresentation:ret];
CFRelease(img);
CFRelease(space);
CGContextRelease(ctx);
}
}
return ret;
}
它的工作,但它会导致内存泄漏。至少在我使用ARC的时候。使用initWithData:[nsimagename TIFFRepresentation]
它无法正常工作。一些图像的表示不好。我认为这取决于图像的格式和色彩空间。有没有其他方法可以实现这一目标?
结果与mrwalker建议解决方案:
原始图像:
转换为bitmapimagerep和回图像1周时间:
转换为位图的处理apimagerep和回图像的3倍:
正如你看到的图像转换为NSBitmapImageRep
后暗每次都使
Hockeyman,你还有完整的解决你的问题?我正在寻找一种方法来识别像素颜色,而不需要太多的过程。也许NSBitmapImageRep可以以某种方式帮助我。谢谢。 – RickON