UIImagePNGRepresentation writeToFile可以捕获错误吗?

时间:2011-12-02 17:32:17

标签: ios png writetofile

我将新收到的PDF文档的缩略图呈现给文档目录。

我正在使用以下代码:

CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("thedoc.pdf"), NULL, NULL);
        CGPDFDocumentRef bookPDF = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
        UIGraphicsBeginImageContext(CGSizeMake(100, 130));
        NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(bookPDF);
        CGContextRef context = UIGraphicsGetCurrentContext();

        for(int i = 0; i < totalNum; i++ ) {
            CGRect arect = CGRectMake(0,0,200,282);
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, 0.0, 141);
            CGContextScaleCTM(context, 1.0, -1.0);
            CGContextSetGrayFillColor(context, 1.0, 1.0);
            CGContextFillRect(context, arect);
            // Grab the first PDF page
            CGPDFPageRef page = CGPDFDocumentGetPage(bookPDF, i + 1);
            CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, arect, 0, true);
            // And apply the transform.
            CGContextConcatCTM(context, pdfTransform);
            CGContextDrawPDFPage(context, page);
            // Create the new UIImage from the context
            UIImage* thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
            if (thumbnailImage == nil) {
                NSLog(@"ERROR during creation of PNG");
            }
            // SAVE THE IMAGE TO DOCUMENTS-DIRECTORY
            NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/thumbPage%i.png",theLocalFolder ,i]];
            // Write image to PNG
            BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath atomically:YES];
            // END SAVE THE IMAGE TO DOCUMENT-DIRECTORY
            CGContextRestoreGState(context);
            NSLog(@"Rendering PDF-Thumbnail %i (%i): %@", i, writtenBool, [NSString stringWithFormat:@"%@/thumbPage%i.png",theLocalFolder ,i]);
        }

控制台中没有错误,但PNG未存储到文档目录中。 BOOL

writtenBool

是“0”,这意味着写入动作不是偶然的。我不知道为什么。我在写道路     pngPath 也到控制台和路径是正确的。如果我打开终端并写

open <<copyed path from console>>

它在finder中打开了正确的路径。

什么可能导致这不起作用?我看了一下api,但似乎没有

error:

for UIImagePNGRepresentation:writeToFile:

感谢您的帮助!

1 个答案:

答案 0 :(得分:6)

UIImagePNGRepresentation(thumbnailImage)返回NSData对象

对于NSData对象,您可以使用以下方法:

writeToFile:atomically:

writeToFile:options:error:

writeToURL:atomically:

writeToURL:options:error:

所以,您可以尝试使用BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath options:NSDataWritingAtomic error:&error];之类的代码来查看发生了什么。