更改从iOS中的PDF中提取的UIImage的颜色

时间:2014-03-14 17:26:59

标签: ios objective-c pdf image-processing uiimage

我有一个PDF文件,我需要从PDF中提取每个页面UIImage,然后根据用户设置更改UIImage的颜色并将其加载到{{1 }}。我有一些如何设法做到这一点,并避免生涩的滚动我预加载一些图像,并在页面传递时释放它们。但是,一旦渲染图像需要大量的内存,并且渲染时间也相当长。请看一下我做过的代码

UICollectionViewCell

任何人都可以帮我减少内存使用量和渲染时间,以便用户可以在页面中平滑滚动。我将页码和颜色选项传递给函数

-(UIImage *)getImageFromPDF:(int)pg withColor:(int)color{ // create PDF document CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:pdfPath]); // get the first page CGPDFPageRef page = CGPDFDocumentGetPage(document, pg); // create a bitmap context CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox); CGFloat pdfScale = 1.0f;//self.view.frame.size.width/pageRect.size.width; pageRect.size = CGSizeMake(pageRect.size.width * pdfScale, pageRect.size.height * pdfScale); UIGraphicsBeginImageContextWithOptions(pageRect.size, YES, pdfScale); // flip the context CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, pageRect.size.height); CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1, -1); // draw the page into the bitmap context CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), page); CGPDFDocumentRelease(document); // get the image from the context UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(color==1) return image; else { CGRect contextRect; contextRect.origin.x = 0.0f; contextRect.origin.y = 0.0f; contextRect.size = [image size]; // Retrieve source image and begin image context CGSize itemImageSize = [image size]; CGPoint itemImagePosition; itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2); itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) ); UIGraphicsBeginImageContext(contextRect.size); CGContextRef c = UIGraphicsGetCurrentContext(); // Setup shadow // Setup transparency layer and clip to mask //CGContextBeginTransparencyLayer(c, NULL); CGContextScaleCTM(c, 1.0, -1.0); CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [image CGImage]); switch (color) { case 1: CGContextSetRGBFillColor(c, 1, 1, 1, 1); break; case 2: CGContextSetRGBFillColor(c, 0, 0, 0, 1); break; case 3: CGContextSetRGBFillColor(c, 0.95686, 0.929412, 0.85098, 1); break; default: CGContextSetRGBFillColor(c, 1, 1, 1, 1); break; } contextRect.size.height = -contextRect.size.height; contextRect.size.height -= 15; // Fill and end the transparency layer CGContextFillRect(c, contextRect); UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; } }

颜色选项1是从PDF中提取的图像的默认颜色,因此跳过着色部分并立即返回-(UIImage *)getImageFromPDF:(int)pg withColor:(int)color。 这是有效的,但需要相当长的时间。任何帮助都非常感谢

1 个答案:

答案 0 :(得分:0)

而不是为函数的每次传递创建CGPDFDocumentRef documentCGContextRef,使用静态或私有属性创建一次。因为创建它们会产生很多内存开销,如果你创建一次,下次它会很快。