Reputation: 9579
I am converting pdf's to images and displaying in ios using quartz 2d api's. The bitmap image width and height will be arbitrary and will not necessarily match the PDF's dimensions.
While most PDF's works just fine, for certain PDF's I only get an empty white image. The bitmap info currently used is kCGImageAlphaNoneSkipLast
. But if I change the bitmap info to kCGImageAlphaPremultipliedLast
or kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big
, the image gets displayed.
I don't get how this works and why it did't work with just kCGImageAlphaNoneSkipLast
. Any thoughts ?
Full Code to convert the PDF to image
#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Load PDF
CFStringRef path = CFStringCreateWithCString(NULL, "/Users/data/input.pdf", kCFStringEncodingMacRoman);
CFURLRef url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, false);
CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL(url);
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, 1);
// Create bitmap
int width = 600;
int height = 600;
int stride = width * 4;
char* buffer = malloc(stride * height);
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
const CGContextRef context = CGBitmapContextCreate(buffer,
width,
height,
8,
stride,
space,
// kCGImageAlphaNoneSkipLast);
// kCGImageAlphaPremultipliedLast);
kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big);
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(context, CGContextGetClipBoundingBox(context));
CGContextDrawPDFPage(context, pdfPage);
CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage *cgimage1 = [UIImage imageWithCGImage:cgImage];
CFRelease(cgImage);
CFRelease(context);
// Display Image
self.myImageView = [[UIImageView alloc] initWithImage:cgimage1];
self.myImageView.center = self.view.center;
self.myImageView.contentMode = UIViewContentModeScaleAspectFit;
self.myImageView.clipsToBounds = YES;
self.myImageView.frame = CGRectMake(10, 20, 600, 600);
[self.view addSubview:self.myImageView];
}
@end
Note: Even tried to save the image to disk and checked. The result was the same.
[UIImagePNGRepresentation(cgimage) writeToFile:@"/Users/data/output.png" atomically:YES];
Upvotes: 2
Views: 182