将NSImage转换为CIImage而不降低质量

时间:2010-09-16 22:38:41

标签: objective-c cocoa core-image

我正在尝试将NSImage转换为CIImage。当我这样做时,图像质量似乎有很大的损失。我认为这是因为“TIFFRepresentation”。有没有人有更好的方法?非常感谢。

NSImage *image = [[NSImage alloc] initWithData:[someSource dataRepresentation]];

NSData  * tiffData = [image TIFFRepresentation];
CIImage *backgroundCIImage = [[CIImage alloc] initWithData:tiffData];

CIContext *ciContext = [[NSGraphicsContext currentContext] CIContext];  
[ciContext drawImage:backgroundCIImage atPoint:CGPointZero fromRect:someRect];

3 个答案:

答案 0 :(得分:1)

您的问题确实转换为TIFF。 PDF是矢量格式,而TIFF是位图,因此TIFF在较大尺寸时看起来会模糊。

你最好的选择可能是从NSImage获得CGImage并从中创建CIImage。或者只是从原始数据创建CIImage。

答案 1 :(得分:0)

尝试替换

NSData  * tiffData = [image TIFFRepresentation];

NSData  * tiffData = [image TIFFRepresentationUsingCompression: NSTIFFCompressionNone factor: 0.0f];

因为the documentation表明TIFFRepresentation使用与每个图像表示相关联的TIFF压缩选项,这可能不是NSTIFFCompressionNone。因此,你应该明确要求tiffData解压缩。

答案 2 :(得分:0)

我终于解决了这个问题。基本上,我将pdf文档渲染为屏幕外正常分辨率的两倍,然后捕获视图显示的图像。要获得更详细的图像,只需增加缩放系数即可。请参阅以下代码以获取概念证明。我没有显示CIImage但是一旦你得到了位图,只需使用CIImage方法从位图创建CIImage。

    NSImage *pdfImage = [[NSImage alloc] initWithData:[[aPDFView activePage] dataRepresentation]];
    NSSize size = [pdfImage size];
    NSRect imageRect = NSMakeRect(0, 0, size.width, size.height);
    imageRect.size.width *= 2; //Twice the scale factor
    imageRect.size.height *= 2; //Twice the scale factor

    PDFDocument *pageDocument = [[[PDFDocument alloc] init] autorelease];
    [pageDocument insertPage:[aPDFView activePage] atIndex:0];

    PDFView *pageView = [[[PDFView alloc] init] autorelease];
    [pageView setDocument:pageDocument];
    [pageView setAutoScales:YES];

    NSWindow *offscreenWindow = [[NSWindow alloc] initWithContentRect:imageRect 
                                                            styleMask:NSBorderlessWindowMask
                                                              backing:NSBackingStoreRetained
                                                                defer:NO];

    [offscreenWindow setContentView:pageView];
    [offscreenWindow display];
    [[offscreenWindow contentView] display]; // Draw to the backing buffer

    // Create the NSBitmapImageRep
    [[offscreenWindow contentView] lockFocus];

    NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:imageRect];

    // Clean up and delete the window, which is no longer needed.
    [[offscreenWindow contentView] unlockFocus];

    [compositeImage TIFFRepresentation]];
    NSData *imageData = [rep representationUsingType: NSJPEGFileType properties: nil];
    [imageData writeToFile:@"/Users/David/Desktop/out.jpg" atomically: YES];

    [offscreenWindow release];