调整PDF NSImage OSX的大小

Mar*_*ges 6 pdf macos nsimage image-resizing

我正在更新调整Mac App的图像.我希望能够做的是,如果用户导入要调整大小的具有PDFImageRep的图像,请保存一个具有我选择的分辨率的新PDF文件.

到目前为止,我已尝试以新的尺寸绘制图像,如:

- (NSImage*)imageAtSize:(NSSize)newSize
{
    NSImage *resizedImage = [[NSImage alloc] initWithSize:newSize];

    [resizedImage lockFocus];
    [self drawInRect:NSMakeRect(0, 0, newSize.width, newSize.height)
            fromRect:NSMakeRect(0, 0, self.size.width, self.size.height)
           operation:NSCompositeSourceOver fraction:1.0];
    [resizedImage unlockFocus];

    return resizedImage;
}
Run Code Online (Sandbox Code Playgroud)

但这会丢失PDF图像代表,因此使我的保存代码失败.

- (void)saveAsPDFWithOutputDirectory:(NSURL *)outputDirectory size:(NSSize)newSize
{
    NSPDFImageRep *pdfRep = [self PDFImageRep];
    [pdfRep setSize:newSize];

    NSError *error = nil;
    [pdfRep.PDFRepresentation writeToURL:outputDirectory options:NSDataWritingAtomic error:&error];
    if (error)
    {
        CLS_LOG(@"Error saving image: %@", error);
    }
}
Run Code Online (Sandbox Code Playgroud)

那我该怎么做呢 我将要使用的图像应该是基于矢量的,所以我是否可以通过某种方式更新PDF上的属性以指定新的分辨率?

Jac*_*ban 1

尝试以下方法。这将创建一个新的 PDF 数据对象,您可以将其保存到文件中。

// pdfData is a CFMutableDataRef
// auxInfo is a CFDictionary
// bounds is your new size in points!
CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData(pdfData);
CGContextRef context = CGPDFContextCreate(consumer, &bounds, auxInfo);
CGPDFContextBeginPage(context, NULL);
NSGraphicsContext *gc = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:gc];

// Your drawing code here
// You probably want to draw your NSImage here in the bounds

[NSGraphicsContext restoreGraphicsState];
CGPDFContextEndPage(context);
CGPDFContextClose(context);
CGContextRelease(context);
CGDataConsumerRelease(consumer);
Run Code Online (Sandbox Code Playgroud)

然后将pdfData保存到文件