How to save PDF to images on OS X? - objective-c

Is there a way to save PDF pages to images on OS X by Xcode 5? I have searched on Stackoverflow and found this Xcode save a PDF as Image?
However it is for iOS, not OS X. I want to export PDF pages to images like JPG or PNG etc.
Thank you in advance.

Try this:
NSData *pdfData = [NSData dataWithContentsOfFile:pathToUrPDF];
NSPDFImageRep *pdfImg = [NSPDFImageRep imageRepWithData:pdfData];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSInteger pageCount = [pdfImg pageCount];
for(int i = 0 ; i < pageCount ; i++) {
[pdfImg setCurrentPage:i];
NSImage *temp = [[NSImage alloc] init];
[temp addRepresentation:pdfImg];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]];
NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSString *pageName = [NSString stringWithFormat:#"Page_%ld.jpg", (long)[pdfImg currentPage]];
[fileManager createFileAtPath:[NSString stringWithFormat:#"%#/%#", #"pathWrUWantToSave", pageName] contents:finalData attributes:nil];
}

Related

writeToFile not properly saving data

I have data from a url (.m4a) and I am trying to save the file so I can edit it's metadata (change background image). The code below doesn't seem to work and I have no idea why. It is saving a file, but the file is empty.
_previewData = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:#"http://a281.phobos.apple.com/us/r1000/119/Music/v4/f1/7b/d6/f17bd6e3-55c0-b7e0-9863-bc522900e950/mzaf_5153970109972844579.aac.m4a"]];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *path = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"file.mp4"]];
NSFileManager *filemanager;
filemanager = [NSFileManager defaultManager];
[_previewData writeToFile:path atomically:YES];
if ([filemanager fileExistsAtPath:path]) {
// Runs
NSLog(#"It worked");
}
NSLog(#"%#",path);
ANMovie* file = [[ANMovie alloc] initWithFile:path]; // or .mp4
NSData* jpegCover = UIImageJPEGRepresentation(artworkImage, 1.0);
_imageView.image = [UIImage imageWithData:jpegCover];
ANMetadata* metadata = [[ANMetadata alloc] init];
metadata.albumCover = [[ANMetadataImage alloc] initWithImageData:jpegCover type:ANMetadataImageTypeJPG];
[file setMovieMetadata:metadata];
[file close];
_previewData = [NSMutableData dataWithContentsOfFile:path];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSDictionary *imageItem=#{#"public.mpeg-4-audio":self.previewData};
NSDictionary *textItem=#{#"public.plain-text":self.linkData};
pasteboard.items=#[imageItem,textItem];

memory leaks issue while saving images to directory

Please try to understand my question.
i am picking images from phone library and saving into Documents Directory. But When I pick large number of images the utilised memory increases gradually and reach above of 400 mb then my app crash. Please if anybody can solve my problem what should I do? I'm new comer to Objective C. Any response will be appreciated.
here is my code
when Picker finish picking
- (void)agImagePickerController:(AGImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info {
[self ShowLoadingView:#"Files Are Loading...."];
[self performSelectorInBackground:#selector(saveAllSelectedImages:) withObject:info];}
and then I save images to Directory
-(void) saveAllSelectedImages:(NSArray*)imagesArray{
for (int i=0; i<imagesArray.count; i++) {
ALAsset *asset = [imagesArray objectAtIndex:i];
ALAssetRepresentation *alassetRep = [asset defaultRepresentation];
NSDate *currentDate = [NSDate date];
NSString* DucPath = [[AppDelegate GetDocumentDirectoryPath] stringByAppendingPathComponent:#"Media"];
if (![[NSFileManager defaultManager] fileExistsAtPath:DucPath])
[[NSFileManager defaultManager] createDirectoryAtPath:DucPath withIntermediateDirectories:NO attributes:nil error:nil];
if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
{
long long DataSize = [alassetRep size];
Byte *buffer = (Byte*)malloc(DataSize);
NSUInteger buffered = (NSUInteger)[alassetRep getBytes:buffer fromOffset:0.0 length:alassetRep.size error:nil];
NSData *videoData = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
NSString* newVideoName = [NSString stringWithFormat:#"video_%d_%d.mov",(int)currentDate,i];
NSString* newVideoPath = [DucPath stringByAppendingPathComponent:newVideoName];
[videoData writeToFile:newVideoPath atomically:YES];
[pImageMediaArray addObject:newVideoName];
}
else
{
UIImage *image = [UIImage imageWithCGImage:[alassetRep fullResolutionImage]];
/************************************Full Resolution Images ******************************************/
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
image = nil;
NSString *originalPath = [NSString stringWithFormat:#"IMAGE_%d_%d.jpg",(int)currentDate,i];
NSString* pImagePath = [DucPath stringByAppendingPathComponent:originalPath];
[imageData writeToFile:pImagePath atomically:YES];
[pImageMediaArray addObject:originalPath];
}
/************************************Low Resolution Images ******************************************/
UIImage *image = [UIImage imageWithCGImage:[alassetRep fullResolutionImage]];
UIImage *thumbImage = [self imageWithImage:image scaledToSize:CGSizeMake(50, 50)];
NSData *thumbImageData = UIImageJPEGRepresentation(thumbImage, 0.8);
NSString *thumbOriginalPath = [NSString stringWithFormat:#"SMALL_IMAGE_%d_%d.jpg",(int)currentDate,i];
NSString* thumbImagePath = [DucPath stringByAppendingPathComponent:thumbOriginalPath];
NSLog(#"Image path At Save Time:%#",thumbImagePath);
[thumbImageData writeToFile:thumbImagePath atomically:YES];
[pMediaArray addObject:thumbOriginalPath];
}
[appDelegate setPMediaArray:pImageMediaArray];
[pGridView reloadData];
imagesArray = nil;
[imagesArray release];
[pImageMediaArray release];
[self performSelectorOnMainThread:#selector(closeLoadindView) withObject:nil waitUntilDone:YES];}
Byte *buffer = (Byte*)malloc(DataSize);
is not being freed?
I had the same exact same issue. What worked for me was to use an autorelease pool block when you save the image. This will free up the retain count and the garbage collection will release the memory appropriately instead of retaining those objects in memory until the containing loop is finished running.
Example: In the method that you are using to save the images add code that looks like this:
#autoreleasepool {
NSString *filePath = [[NSArray arrayWithObjects:self.imagePath, #"/", GUID, #".png", nil] componentsJoinedByString:#""];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
BOOL res = [imageData writeToFile:filePath atomically:YES];
imageData = nil;
}
You need to add the autoreleasepool for task that perform in the background. In the above code content of the saveAllSelectedImages should be written inside autoreleasepool, Otherwise memory won't be released.

Save to a custom photo folder IOS 7.1

Is there a way to disable the "Saved Photos" folder when saving an image?
NSData *data1 = UIImagePNGRepresentation(imageToCrop.image);
UIImage *tehnewimage = [UIImage imageWithData: data1];
[self.library saveImage:tehnewimage toAlbum:#"Databender Edits" withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(#"eRrOr: %#", [error description]);
}
}];
If you are using ALAssetsLibrary to manage your apps photos, then they will always show under saved photos. According to the Apple Docs the purpose of ALAssetsLibrary is
You use it to retrieve the list of all asset groups and to save images and videos into the Saved Photos album.
If you only need your images accessible inside your app you can handle the reading writing, and presenting of them yourself. This would prevent them from showing up in the camera role or saved photos.
//WRITING TO APP DIRECTORY
NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:#"Photos/"];
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]){
NSError* error;
[[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error];
}
NSData *imgData = UIImagePNGRepresentation(imageToCrop.image);
NSString *imgName = #"example.png";
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:imgName];
[imgData writeToFile:pngPath atomically:YES];
//READING FROM APP DIRECTORY
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:#"/Photos/"] error:NULL];
for (int i = 0; i < (int)[directoryContent count]; i++)
{
NSURL *url = [NSURL URLWithString:[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"/Documents/Photos/%#",[directoryContent objectAtIndex:i]]]];
UIImage *image = [UIImage imageWithContentsOfFile:[url absoluteString]];
//ADD IMAGE TO TABLE VIEW OR HANDLE HOW YOU WOULD LIKE
}

Not able to display images from particular directory IOS

I'm trying to create image from this location :
NSString *documentsCacheDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *fileName = #"image1.jpg";
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsCacheDirectory, fileName];
So applying to my Image :
UIImage *myImage = [UIImage imageNamed:filePath];
..setting this image as background to my button etc. etc.
But I'm not seeing any images displayed. However when I use the same technique for reading a file :
NSString *documentsCacheDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *fileName = #"file.txt";
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsCacheDirectory, fileName];
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [cacheFileContents componentsSeparatedByString:#"\n"]) {
.....
}
Reading file works just fine, but image does not, any reasons why?
imageNamed: is for images that are bundled with your app, you don't use this with a path. Use imageWithContentsOfFile: instead.

Image not saving in Objective C

I am downloading a file using the following:
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"URL HERE"]];
Displaying it with the following:
UIImage *img = [UIImage imageWithData:imgData];
And saving it to the device with the following:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pth = [[paths objectAtIndex:0] stringByAppendingPathComponent:self.localFile];
NSData *d1 = [NSData dataWithData:UIImageJPEGRepresentation(img,1.0f)];
[d1 writeToFile:pth atomically:YES];
Photo displays fine in my UIImageView. But when I reload the application and display the file, I get the following error:
ImageIO: CGImageRead_mapData 'open' failed '/var/mobile/Applications/422122E1-3244-46CE-BB6C-123C750E2191/Documents/14741078_1.jpg'
error = 2 (No such file or directory)
ImageIO: <ERROR> JPEGNot a JPEG file: starts with 0xff 0xd9
I have just resolved the same issue.
Don't change your load method.
But save your image like this :
NSError* error = nil;
[UIImageJPEGRepresentation(img, 1.0f) writeToFile:pth options:NSDataWritingAtomic error:&error];