NSImage转换为NSBitmapImageRep

16

如何将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建议的结果:
原始图像:
enter image description here 转换为位图图像表示并再次转换为图像1次:
enter image description here 转换为位图图像表示并再次转换为图像3次:
enter image description here 如您所见,每次将其转换为NSBitmapImageRep后,图像都会变暗。

Hockeyman,你还有完整的解决方案吗?我正在寻找一种不需要太多处理就能识别像素颜色的方法。也许NSBitmapImageRep可以在某种程度上帮助我。谢谢。 - RickON
你正在进行一些颜色空间转换,颜色空间转换通常不是无损的,因为它经常涉及浮点计算,后来需要舍入回整数值。随着时间的推移,你会有越来越多的舍入误差。尽管如此,你的代码过于复杂,可以在这里查看:https://dev59.com/pmMm5IYBdhLWcg3wlftS#17510651 - Mecki
3个回答

16

@Julius:你的代码过于复杂,而且含有几个错误。我将仅对前几行进行纠正:

- (NSBitmapImageRep *)bitmapImageRepresentation
{
   for( NSImageRep *rep in [self representations] )
      if( [rep isKindOfClass:[NSBitmapImageRep class]] ) return rep;
   return nil;
}
这将提取第一个NSBitmapImageRep,如果它是表示中的成员,或者如果没有NSBitmapImageRep,则返回nil。我会给你另一个解决方案,无论representations中有哪些NSImageReps,它都可以工作: NSBitmapImageRepNSPDFImageRepNSCGImageSnapshotRep或...
- (NSBitmapImageRep *)bitmapImageRepresentation
{
   CGImageRef CGImage = [self CGImageForProposedRect:nil context:nil hints:nil];
   return [[[NSBitmapImageRep alloc] initWithCGImage:CGImage] autorelease];
}

或者为了避免继承NSImage,您可以编写:

NSImage *img = [[[NSImage alloc] initWithContentsOfFile:filename] autorelease];
CGImageRef CGImage = [img CGImageForProposedRect:nil context:nil hints:nil];
NSBitmapImageRep *rep = [[[NSBitmapImageRep alloc] initWithCGImage:CGImage] autorelease];

如果图像包含多个表示(例如,来自TIFF文件的许多NSBitmapImageRep),则此方法仅会返回单个NSBitmapImageRep,这可能不够好。但是添加一些代码很简单。


1
作为额外的建议,您可能希望在迭代中将第二个 [self representations] 替换为 ret,因为目前 ret 没有被使用。 - Brad Larson
请注意,如果图像是从头创建而不是从文件加载的,则可能没有任何图像表示。 - Ash
谢谢!如果没有强制转换,第一段对我来说是无效的:if( [rep isKindOfClass:[NSBitmapImageRep class]] ) return (NSBitmapImageRep *)rep; - idbrii

14

您可以尝试使用从Mike Ash的“获取并解释图像数据”博客文章改编的此方法:

- (NSBitmapImageRep *)bitmapImageRepresentation {
  int width = [self size].width;
  int height = [self size].height;

  if(width < 1 || height < 1)
      return nil;

  NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
                           initWithBitmapDataPlanes: NULL
                           pixelsWide: width
                           pixelsHigh: height
                           bitsPerSample: 8
                           samplesPerPixel: 4
                           hasAlpha: YES
                           isPlanar: NO
                           colorSpaceName: NSDeviceRGBColorSpace
                           bytesPerRow: width * 4
                           bitsPerPixel: 32];

  NSGraphicsContext *ctx = [NSGraphicsContext graphicsContextWithBitmapImageRep: rep];
  [NSGraphicsContext saveGraphicsState];
  [NSGraphicsContext setCurrentContext: ctx];  
  [self drawAtPoint: NSZeroPoint fromRect: NSZeroRect operation: NSCompositeCopy fraction: 1.0];
  [ctx flushGraphics];
  [NSGraphicsContext restoreGraphicsState];

  return [rep autorelease];
}

这个方法可以工作,但是不正确。它返回的图像颜色较暗。我会在我的问题中添加一个例子。 - hockeyman
如果使用NSDeviceRGBColorSpace而不是NSCalibratedRGBColorSpace,结果会更好吗? - mrwalker
不用谢。我更新了我的答案,也使用了NSDeviceRGBColorSpace。 - mrwalker

3
也许有点晚了,但这是 @mrwalker 回复的 Swift 3 版本:
extension NSImage {
    func bitmapImageRepresentation(colorSpaceName: String) -> NSBitmapImageRep? {
        let width = self.size.width
        let height = self.size.height

        if width < 1 || height < 1 {
            return nil
        }

        if let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: colorSpaceName, bytesPerRow: Int(width) * 4, bitsPerPixel: 32)
        {
            let ctx = NSGraphicsContext.init(bitmapImageRep: rep)
            NSGraphicsContext.saveGraphicsState()
            NSGraphicsContext.setCurrent(ctx)
            self.draw(at: NSZeroPoint, from: NSZeroRect, operation: NSCompositingOperation.copy, fraction: 1.0)
            ctx?.flushGraphics()
            NSGraphicsContext.restoreGraphicsState()
            return rep
        }
        return nil
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接