【发布时间】:2012-10-15 13:38:44
【问题描述】:
如何将 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 次:
转换为bitmapimagerep并返回图像3次:
如您所见,每次转换为 NSBitmapImageRep 后图像都会变暗
【问题讨论】:
-
Hockeyman,您的问题还有完整的解决方案吗?我正在寻找一种无需太多过程即可识别像素颜色的方法。也许 NSBitmapImageRep 可以以某种方式帮助我。谢谢。
-
您正在进行一些色彩空间转换,色彩空间转换通常不是无损的,因为它通常涉及浮点计算,稍后需要将其四舍五入为整数值。随着时间的推移,你会得到越来越多的舍入错误。你的代码太复杂了,看这里:stackoverflow.com/a/17510651/15809
标签: objective-c macos bitmap nsimage nsbitmapimagerep