Search code examples
objective-cmacosnsimagecgimage

Can any code replace "imageWithSize" on Xcode?


I have used [NSImage imageWithSize: method to draw NSPDFImageRep to images. However imageWithSize method can be only used on mac os x 10.8 or higher. Is there a way to replace this method and use for 10.6 and 10.7 ? Is it possible to use CGImage or something?

Code:

NSString* localDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString* pdfPath = [localDocuments stringByAppendingPathComponent:@"1.pdf"];
NSData* pdfData = [NSData dataWithContentsOfFile:pdfPath];
NSPDFImageRep* pdfImageRep = [NSPDFImageRep imageRepWithData:pdfData];
CGFloat factor = 300/72;
NSInteger pageCount = [pdfImageRep pageCount];
for(int i = 0 ; i < pageCount ; i++)
{
    [pdfImageRep setCurrentPage:i];
    NSImage* scaledImage = [NSImage imageWithSize:pdfImageRep.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
        [pdfImageRep drawInRect:dstRect];
        return YES;
    }];
    NSImageRep* scaledImageRep = [[scaledImage representations] firstObject];
    /*
     * The sizes of the PDF Image Rep and the [NSImage  imageWithSize: drawingHandler:]-context
     * are define in terms of points.
     * By explicitly setting the size of the scaled representation in in Pixels, you 
     * define the relation between ponts & pixels.
     */
    scaledImageRep.pixelsWide = pdfImageRep.size.width * factor;
    scaledImageRep.pixelsHigh = pdfImageRep.size.height * factor;
    NSBitmapImageRep* pngImageRep = [NSBitmapImageRep imageRepWithData:[scaledImage TIFFRepresentation]];
    NSData* finalData = [pngImageRep representationUsingType:NSJPEGFileType properties:nil];
    NSString* pageName = [NSString stringWithFormat:@"Page_%ld.jpg", (long)[pdfImageRep currentPage]];
    [[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@%@", pdfPath, pageName] contents:finalData attributes:nil];
}

Solution

  • I think this should be right.

        NSImage* scaledImage;
        if ([NSImage respondsToSelector:@selector(imageWithSize:flipped:drawingHandler:)]) { //Check if the os supports it
             scaledImage = [NSImage imageWithSize:pdfImageRep.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
                  [pdfImageRep drawInRect:dstRect];
                  return YES;
             }];
    
        } else { //use old drawing method
             scaledImage = [[[NSImage alloc] initWithSize:pdfImageRep.size] autorelease];
             [scaledImage lockFocus];
             [pdfImageRep drawInRect:dstRect];
             [scaledImage unlockFocus];
        }