Convert PDF pages to images with COCOA - cocoa

I am having problem with PDF conversion to images. I would like to create an image file for every page in PDF document.
This is the code I am using and works fine. Every page gets converted into the image, but I have problem with image resolution. I don't know how to set the resolution of the output images. Can someone help me out?
NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost/test/test.pdf"]];
NSPDFImageRep *img = [NSPDFImageRep imageRepWithData:pdfData];
NSFileManager *fileManager = [NSFileManager defaultManager];
int count = [img pageCount];
for(int i = 0 ; i < count ; i++) {
[img setCurrentPage:i];
NSImage *temp = [[NSImage alloc] init];
[temp addRepresentation:img];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]];
NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSString *pageName = [NSString stringWithFormat:#"Page_%d.jpg", [img currentPage]];
[fileManager createFileAtPath:[NSString stringWithFormat:#"%#/%#", #"/Users/mac/Desktop/", pageName] contents:finalData attributes:nil];
}
Thanks a lot!

Since NSPDFImageRep is a subclass of NSImageRep, couldn't you use the [NSImageRep drawInRect:] method?
Link: http://developer.apple.com/mac/library/documentation/cocoa/reference/ApplicationKit/Classes/NSImageRep_Class/Reference/Reference.html#//apple_ref/doc/uid/20000346-drawInRect_

The simplest way would be to use the ImageIO framework. Feed the PDF data to an image source to get a CGImage; feed that object to an image destination to generate (and optionally save in the same step) the JPEG data. In the latter step, you can specify the resolution among the image properties; see “Individual Image Properties” in the documentation.
Don't forget to finalize your destination. It's vital.

Related

How to handle multiple images with large size?

I have list of selected images from Photos gallery.
The array list contain selected PHAssets from Photos
<PHAsset: 0x131334350> 768AD8BA-FE7A-4EE9-B2CF-4DD4AEBE2AE9/L0/001 mediaType=1/0, sourceType=1, (2448x3264), creationDate=2016-03-11 06:50:09 +0000, location=1, hidden=0, favorite=0 ",
"<PHAsset: 0x131334260> CA962E42-A367-4E8D-85C8-934F8C76FE78/L0/001 mediaType=1/0, sourceType=1, (2448x3264), creationDate=2016-03-11 06:50:08 +0000, location=1, hidden=0, favorite=0 "
Now i want to store this images into Document Directory.For that i am converting PHAssets to original image and store it in array, for that code i did
#property (nonatomic, strong) PHImageRequestOptions *requestOptions;
for (PHAsset *asset in assetArray) {
self.requestOptions = [[PHImageRequestOptions alloc] init];
self.requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
self.requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
// this one is key
self.requestOptions.synchronous = true;
PHImageManager *manager = [PHImageManager defaultManager];
__block UIImage *ima;
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:self.requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[Albumimages addObject:ima];
}];
}
But problem is that when i selected multiple images with large size(more than 25) app is crash down. Because when i convert PHAsset to original image by using PHImageManager it uses high memory of device.
Please help me to solve this problem. Provide me if there is any other solution to handle selected PHAssets for storing images in application document directory.
PHImageRequestOptions *option = [PHImageRequestOptions new];
option.synchronous = NO;
let screenSize: CGSize = UIScreen.mainScreen().bounds.size
let targetSize = CGSizeMake(screenSize.width, screenSize.height)
[manager requestImageForAsset:asset
targetSize:target
contentMode:PHImageContentModeAspectFill
options:option resultHandler:^(UIImage *result, NSDictionary *info)
{
//this block will be called synchronously
}];
If you set maximum image size when using more images they could crash but if set target size then handles it.
Handle all images with the data instead of covert into original image.
[manager requestImageDataForAsset:asset
options:self.requestOptions
resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info)
{
// UIImage *image = [UIImage imageWithData:imageData];
[Albumimages addObject:imageData];
}];
After that Write image data at document directory path.

How to draw EPS data on NSView

I'm struggling with the problem to draw an eps file on a NSView.
When I first load the eps file from a file and draw it with drawInRect: the image is displayed correctly. However, the image will not be drawn when I load it from an archive file.
I've prepared a dirty small example that you can copy/paste and try out. Create a new Cocoa App project and add this to the delegate method.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Just a sample eps file
NSURL *url = [NSURL URLWithString: #"http://embedded.eecs.berkeley.edu/concurrency/latex/figure.eps"];
NSImage *epsImage = [[[NSImage alloc] initWithContentsOfURL: url] autorelease];
// Encode data
NSMutableData *mutableData = [[[NSMutableData alloc] init] autorelease];
NSKeyedArchiver *coder = [[[NSKeyedArchiver alloc] initForWritingWithMutableData: mutableData] autorelease];
[coder encodeObject: epsImage forKey: #"image"];
[coder finishEncoding];
NSString *dataFile = [#"~/Desktop/image.data" stringByExpandingTildeInPath];
[mutableData writeToFile: dataFile atomically: YES];
// Decode data
NSData *data = [NSData dataWithContentsOfFile: dataFile];
NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData: data];
NSImage *loadedImage = [decoder decodeObjectForKey: #"image"];
// Draw image
NSRect rect;
rect.origin = NSZeroPoint;
rect.size = loadedImage.size;
NSView *view = [[NSApp mainWindow] contentView];
[view lockFocus];
[loadedImage drawInRect: rect fromRect: rect operation: NSCompositeSourceOver fraction: 1.0];
[view unlockFocus];
}
To prove that the first loaded image draws correctly just change the line [loadedImage drawInRect:...] to [epsImage drawInRect:...].
I'm using NSKeyedArchiver and NSKeyedUnarchiver here for simulating encodeWithCoder: and initWithCoder:. So please focus on the fact that NSImage with NSEPSImageRep representation, which does not contain a preview (from a resource fork?) and loaded purely as eps commands, is not drawn on a NSView correctly.
Any help is appreciated.
Due to the way that cacheing works on NSImage, I've often found it more effective to actually grab the NSImageRep if I know what the type is.
In our code, we found that the most reliable way to save off images is in their original format, but that requires either saving off the data in its original format somewhere else, or requesting the data from the NSImageRep. Unfortunately, there's not a generic -(NSData*)data method of NSImageRep, so we ended up specifically checking for various types of NSImageRep and saving them off depending on what we knew them to be.
Fortunately, loading is simple, as NSImage::initWithData: will figure out the type based on the data.
Here's our long-standing code for doing this. Basically, it prefers PDF then EPS then it makes a TIFF of anything it doesn't understand.
+ (NSData*) dataWithImage:(NSImage*)image kindString:( NSString**)kindStringPtr
{
if (!image)
return nil;
NSData *pdfData=nil, *newData=nil, *epsData=nil, *imageData=nil;;
NSString *kindString=nil;
NSArray *reps = [image representations];
for (NSImageRep *rep in reps) {
if ([rep isKindOfClass: [NSPDFImageRep class]]) {
// we have a PDF, so save that
pdfData = [(NSPDFImageRep*)rep PDFRepresentation];
PDFDocument *doc = [[PDFDocument alloc] initWithData:pdfData];
newData = [doc dataRepresentation];
if (newData && ([newData length]<[pdfData length])) {
pdfData = newData;
}
break;
}
if ([rep isKindOfClass: [NSEPSImageRep class]]) {
epsData = [(NSEPSImageRep*)rep EPSRepresentation];
break;
}
}
if (pdfData) {
imageData=pdfData;
kindString= #"pdfImage";
} else if (epsData) {
imageData=epsData;
kindString=#"epsImage";
} else {
// make a big copy
NSBitmapImageRep *rep0 = [reps objectAtIndex:0];
if ([rep0 isKindOfClass: [NSBitmapImageRep class]]) {
[image setSize: NSMakeSize( [rep0 pixelsWide], [rep0 pixelsHigh])];
}
imageData = [image TIFFRepresentation];
kindString=#"tiffImage";
}
if (kindStringPtr)
*kindStringPtr=kindString;
return imageData;
}
Once we have the NSData*, it can be saved in a keyed archive, written to disk or whatever.
On the way back in, load in the NSData* and then
NSImage *image = [[NSImage alloc] initWithData: savedData];
and you should be all set.

WebView to TIFF representation

I'm trying to capture the contents of a WebView and saving it as an image. This is my code right now (cv is the web view):
[cv lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[cv bounds]];
[cv unlockFocus];
NSData *data = [rep TIFFRepresentation];
[data writeToFile:[[save URL] path] atomically:NO];
All I get is a gray image with the correct size. What am I doing wrong?
I don't think you are using correctly NSBitmaImageRep.
Have a look at this post for a couple of ways of doing what you are trying to. Possibly the only one that is working for a web view (which is quite a complex beast) is the screenshot+crop approach.

Xcode save and load image in Xcode iOS

Check my app if you don't really understand ( Quick Notes!) But here it goes. My app is a notes app so it allows the user to select from few different kinds of note colors and designs below. When the user selects one, it changes the note above to what ever they set it to. So i need a button that will save the picture they selected, and when the leave the view and come back they can click the load button and the same image they selected will appear. I am using Xcode 4.3. Thanks so much!
Here is my save code:
-(IBAction)save123456 {
NSBitmapImageRep *rep;
NSData *data;
NSImage *noteview;
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
[self unlockFocus];
image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
[image addRepresentation:rep];
data = [rep representationUsingType: NSPNGFileType properties: nil];
//save as png but failed
[data writeToFile: #"asd.png" atomically: NO];
//save as pdf, succeeded but with flaw
data = [self dataWithPDFInsideRect:[self frame]];
[data writeToFile:#"asd.pdf" atomically:YES];
}
And my load:
-(IBAction)load123456 {
NSImage loadedImage = [[NSImage alloc] initWithContentsOfFile: NSString* filePath]
}
I get so many error codes in my save. My image is called noteview. Thanks!!
Try use instead
[data writeToFile: #"asd.png" atomically: NO];
a code line
[data writeToFile: #"asd.png" atomically: YES];
Some open source examples:
AGSimpleImageEditorView
image editors in iOS
projects with work with Pictures

What format is person's ImageData(CFDataRef) in AddressBook?(Jpeg or PNG)?Or how to determine?

From AddressBook's API ABPersonCopyImageData I can get a CFDateRef which is toll-free bridge to NSData. And I want to write this data to file, but what file extension should I use ?
.jpeg or .png?
The documentation doesn't mention what the data is.Is there any way to know?
NSData *imgData = (__bridge NSData *)ABPersonCopyImageData(person);
UIImage *img = [UIImage imageWithData:imgData];
if (!img) {
img = [UIImage imageNamed:#"noImage.png"];
}

Resources