大家好,我正在尝试从 pdf 为我的应用程序创建 PNG(缩略图)图像,因为我使用了下面代码中 stackoverflow 的几个答案,我正在使用 `-
-(void)pdfToImageConverter{
NSURL* pdfFileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"ebook" ofType:@"pdf"]];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);
CGPDFPageRef page;
CGRect aRect = CGRectMake(0, 0, 100, 200); // thumbnail size
NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);
for(int i = 0; i < totalNum; i++ ) {
CGPDFPageRef myPageRef=CGPDFDocumentGetPage(pdf, i+1);
aRect=CGPDFPageGetBoxRect(myPageRef, kCGPDFCropBox);
UIGraphicsBeginImageContext(CGSizeMake(383, 383*(aRect.size.height/aRect.size.width)));
CGContextRef context = UIGraphicsGetCurrentContext();
UIImage* thumbnailImage;
//thumbnailImage=[[UIImage alloc] init];
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, aRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextFillRect(context, aRect);
// Grab the PDF page
page = CGPDFDocumentGetPage(pdf, i + 1);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, aRect, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
CGContextDrawPDFPage(context, page);
// Create the new UIImage from the context
thumbnailImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
//Use thumbnailImage (e.g. drawing, saving it to a file, etc)
CGContextRestoreGState(context);
NSString *documentsPath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingFormat:@"/page_%d.png",i+1];
NSData *imagedata;//=[[NSData alloc] init];
imagedata=[UIImagePNGRepresentation(thumbnailImage) retain];
[thumbnailImage release];
[imagedata writeToFile:documentsPath atomically:YES];
[imagedata release];
UIGraphicsEndImageContext();
}
CGPDFDocumentRelease(pdf);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"message" message:@"images creation completed" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
[alert show];
[alert release];
}`
*问题:*上面的代码在模拟器中运行良好,它在用于创建一些图像的设备中运行(最多 30 个缩略图)。我使用分析器检查内存泄漏,但上面的代码没有泄漏,但我仍然无法创建所有缩略图。我正在使用包含 1037 页的 ebook.pdf(300MB)。所以我需要 1037 个缩略图。
*问题 : *
1.代码有问题吗?
2.我在上面的代码块中做错了什么?
3.是否有任何其他机制可以从 PDF 创建 png 图像?
在此先感谢,您的建议对我来说更重要。
最佳答案
千页循环意味着您为每个页面进程分配内存,并且在方法结束之前永远不会重用该内存块。 Obj-C 内存管理就是这样工作的,每次循环后都会有效地释放内存。
如果要为每次迭代重用内存,请使用独立的 NSAutoreleasePool
for(int i = 0; i < totalNum; i++ ) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
... .... (process page ... ) ...
[pool release];
}
或者,如果您使用 ARC:
for(int i = 0; i < totalNum; i++) {
@autoreleasePool {
.... (... process page ... ) ....
}
}
关于iphone - 在ios中创建PDF到图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8652472/