How to convert a NSData to pdf in iPhone sdk? - iphone

Am converting a webpage as a pdf file. I did the following,
NSString *string=[NSString stringWithFormat:#"%#.pdf",[chapersArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:#"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[controller1 release];
Now how can i convert my NSData into pdf and save in my application memory? Kindly help me with sample codes or suggestions. Thanks all.

Am assuming you have your pdf in documents directory here. You can change it to where ever it actually is. Try this -
//to convert pdf to NSData
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"test.pdf"];
NSData *myData = [NSData dataWithContentsOfFile:pdfPath];
Essentially using CGPDFDocumentCreateWithProvider you can convert NSData to pdf,
//to convert NSData to pdf
NSData *data = //some nsdata
CFDataRef myPDFData = (CFDataRef)data;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
Don't forget to CFRelease all unused data after you are done.

I got this is in a simple method as follows,
-(IBAction)saveasPDF:(id)sender{
NSString *string=[NSString stringWithFormat:#"%#.pdf",[chapersArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:#"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[pdfData writeToFile:[self getDBPathPDf:string] atomically:YES];
}
-(NSString *) getDBPathPDf:(NSString *)PdfName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:PdfName];
}

You can try with this solution:
- (void)saveDataToPDF:(NSData *)pdfDocumentData
{
//Create the pdf document reference
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)pdfDocumentData);
CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(dataProvider);
//Create the pdf context
CGPDFPageRef page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CFMutableDataRef mutableData = CFDataCreateMutable(NULL, 0);
//NSLog(#"w:%2.2f, h:%2.2f",pageRect.size.width, pageRect.size.height);
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);
if (CGPDFDocumentGetNumberOfPages(document) > 0)
{
//Draw the page onto the new context
//page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1
CGPDFContextBeginPage(pdfContext, NULL);
CGContextDrawPDFPage(pdfContext, page);
CGPDFContextEndPage(pdfContext);
}
else
{
NSLog(#"Failed to create the document");
}
CGContextRelease(pdfContext); //Release before writing data to disk.
//Write to disk
[(__bridge NSData *)mutableData writeToFile:#"/Users/David/Desktop/test.pdf" atomically:YES];
//Clean up
CGDataProviderRelease(dataProvider); //Release the data provider
CGDataConsumerRelease(dataConsumer);
CGPDFDocumentRelease(document);
CFRelease(mutableData);
}

Related

pdf show in simulator but not in iPhone

I am struggling with the problem from last few hour. I make a pdf programmatically and save it on ~/library/Application Support/iPhone Simulator/... and the programs work fine for me in simulator. I can save and retrieve the pdf in webView.
But when I test my App in iPhone4 device I not see the pdf file when I retrieve. I am new so I don't know check manually that pdf created in device or not.
Please provide me help.
thanks
I save the pdf from this code :
- (void)generatePdfButtonPressed{
pageSize = CGSizeMake(612, 792);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[self generatePdfWithFilePath:pdfFileName];
}
- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
NSInteger currentPage = 0;
BOOL done = NO;
do
{
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
// Draw a page number at the bottom of each page.
currentPage++;
//[self drawPageNumber:currentPage];
//Draw a border for each page.
// [self drawBorder];
//Draw text fo our header.
[self drawHeader];
//Draw a line below the header.
[self drawLine];
//Draw personel details
[self drawPersonelDetail];
//Draw Education
[self drawEducation];
//Draw work Experiences
[self drawWorkExperiences];
//Draw work Activities
[self drawActivities];
//Draw Skills
[self drawSkils];
//Draw some text for the page.
// [self drawText];
yCord=550;
// [self drawText];
//Draw an image
// [self drawImage];
done = YES;
}
while (!done);
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
}
After a long struggling I find the solution of my own question : I provide solution below may be it help any other.
- (void)generatePdfButtonPressed{
pageSize = CGSizeMake(612, 792);
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
[self generatePdfWithFilePath:pdfFileName];
}
- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
NSInteger currentPage = 0;
BOOL done = NO;
do
{
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
// Draw a page number at the bottom of each page.
currentPage++;
[self drawPageNumber:currentPage];
//Draw a border for each page.
[self drawBorder];
//Draw text our header.
[self drawHeader];
//Draw a line below the header.
[self drawLine];
//Draw personel details
[self drawPersonelDetail];
//Draw Education
[self drawEducation];
//Draw an image
[self drawImage];
done = YES;
}
while (!done);
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
}
And for Display the pdf file the method is :
- (void)showPdfClicked
{
pdf1View.scalesPageToFit = YES;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"%#",documentsDirectory);
NSString *path1 =[documentsDirectory stringByAppendingPathComponent:#"Demo.pdf"];
NSLog(#"Retruve Save path is %#: ",path1);
// NSString *path1 = [[NSBundle mainBundle] pathForResource:#"pdf1" ofType:#"pdf"];
NSURL *targetURL1 = [NSURL fileURLWithPath:path1];
NSURLRequest *request1 = [NSURLRequest requestWithURL:targetURL1];
[pdf1View loadRequest:request1];
}
I've run into this problem before. My guess is it's a memory issue--how large is the PDF file you're trying to load? UIWebView seems to have have some issues buffering (if it does this at all) large files for display.
I successfully send my created pdf by email through this code. May Be this helps you(dottorfeelgood).
-(IBAction)emailButtonClicked
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Subject"];
NSString *fileName = #"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
NSMutableData *pdfData = [NSMutableData data];
pdfData = [NSData dataWithContentsOfFile:pdfFileName];
CGRect bounds=CGRectMake(0, 0, 612, 792);
[picker addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"SomeFile.pdf"];
// Fill out the email body text
NSString *emailBody = #"Image is attached";
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
//[picker release];
}
Happy Coding!!!

Download Image and UIButton BG image

I am trying to do download some images from server then , set these images as background image for some UIButtons .
so first downloading images :
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSString *str = [NSString stringWithFormat:urlMag1,urlMag2,nil];
NSData *data = [NSData dataWithContentsOfFile:str];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[data writeToFile:path atomically:YES];
UIImage *imgMag1 = [UIImage imageNamed:#"i224_mag2.png"];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
but nothing happens !!,and how can I check to if these images are in directory to avoid more downloading
I would be grateful if you help me to solve this
thanks !
EDITED
#Fernando Cervantes
I created a method to set buttons BG images something like this , but I don't know why does not work !
- (UIImage *)loadImages :(NSString *)fileNames ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
[[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileNames, extension]]];
return 0;
}
and set BG images :
- (void)buttonsBGImage {
UIImage * bgMag2 = [self loadImages:#"i224_mag2" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[mag2 setBackgroundImage:bgMag2 forState:UIControlStateNormal];
}
but actually nothing happens ! even I check the file and it's in app directory
The following approach might help you out a bit.
Save
-(void) saveFile:(NSString *)fileName ofType:(NSString *)extension fromURL:(NSString *)fileIndexPath inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileIndexPath]];
[data writeToFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension] atomically:YES];
}
Check
-(BOOL) checkIfFileExists:(NSString *)fileName ofType:(NSString *)extension inDirectoryPath:(NSString *)directoryPath {
bool result;
if ([[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileName, extension]]]) {
result = TRUE;
} else {
result = FALSE;
}
return result;
}
Set
UIButton * button = [[UIButton alloc] init];
UIImage * backgroundImage = [self loadImage:#"YourImageName" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[button setImage:backgroundImage forState:UIControlStateNormal];
-Edited-
I believe your problem is that you are returning 0 in your loadImages method. Instead of returning the image itself.
This is how I accomplished it:
Load
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}
[UIImage imageNamed:#"i224_mag2.png"]; // it is only for bundle. You should use
[UIImage imageWithContentsOfFile:path]
or
[UIImage imageWithData:data];
Update:
I use category for UIButton class.
- (void)loadImage:(NSString *)URL withActivityIndicator:(BOOL)hasActivity refreshObject:(UIView *)refresh{
// load image from cache cutted
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:URL]];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *loadedImage = [UIImage imageWithData:image];
// add image to cache cutted
[self setImage:loadedImage forState:UIControlStateNormal];
});
});
}
You are making NSData using dataWithContentsOfFile: API. you should use dataWithContentsOfURL instead.
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSData *image1 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]];
NSData *image2 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag2]];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
Usually [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]]; will freeze UI until image downloading complete.

What is the correct way to import & save Photos from iPhone Album?

I am Importing Photos from the iPhone Album to the documents folder of my application. This is my code.
for (int j=0; j<[assetArray count]; j++) {
ALAsset *assest = [assetArray objectAtIndex:j];
CGImageRef imageRef = assest.defaultRepresentation.fullResolutionImage;
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImageJPEGRepresentation(image);
[imageData writeToFile:documentsPath atomically:YES];
}
Its working fine but when I try to Import higher resolution Images it takes more time. What is the correct way to Import with least time? BTW: It takes more time when I convert the image into NSData.
It's dangerous to use the fullResolutionImage for this task for several reasons.
Some remarks:
For large images memory problems could occur. when using the fullResolutionImage method. Please note, that the Photo-Library (on the iPad at least) can also contain RAW-images.
The performance is suboptimal as internally from the imagefile ImageIO creates first a CGImageRef that is then converted to a JPEG. This takes time.
The AssetLibrary can also contain videos. In such a case fullResolutionImage only returns a previewImage of the video, but not the actual video.
It's no problem to store the actual Asset-Objects as these are small in memory.
A far better approach to write out the images to the documents directory, would be to use the getBytes method of ALAssetsRepresentation. This should be way faster and more efficient memory wise. It also gives you the original image file (incl. metadata) and also works for videos.
Your example code rewritten then would look like that:
//reading out the orginal images
for (int j=0; j<[assetArray count]; j++) {
ALAssetRepresentation *representation = [[assetArray objectAtIndex:j] defaultRepresentation];
NSString* filename = [documentPath stringByAppendingPathComponent:[representation filename]];
[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil];
NSOutputStream *outPutStream = [NSOutputStream outputStreamToFileAtPath:filename append:YES];
[outPutStream open];
long long offset = 0;
long long bytesRead = 0;
NSError *error;
uint8_t * buffer = malloc(131072);
while (offset<[representation size] && [outPutStream hasSpaceAvailable]) {
bytesRead = [representation getBytes:buffer fromOffset:offset length:131072 error:&error];
[outPutStream write:buffer maxLength:bytesRead];
offset = offset+bytesRead;
}
[outPutStream close];
free(buffer);
}
//reading out the fullScreenImages and thumbnails
for (int j=0; j<[assetArray count]; j++)
{
#autoreleasepool
{
ALAsset *asset = [assetArray objectAtIndex:j];
NSString *orgFilename = [representation filename];
NSString *filenameFullScreen = [NSString stringWithFormat:#"%#_fullscreen.png",[orgFilename stringByDeletingPathExtension]]
NSString* pathFullScreen = [documentPath stringByAppendingPathComponent:filenameFullScreen];
CGImageRef imageRefFullScreen = [[asset defaultRepresentation] fullScreenImage];
UIImage *imageFullScreen = [UIImage imageWithCGImage:imageRefFullScreen];
NSData *imageDataFullScreen = UIImagePNGRepresentation(imageFullScreen);
[imageDataFullScreen writeToFile:pathFullScreen atomically:YES];
NSString *filenameThumb = [NSString stringWithFormat:#"%#_thumb.png",[orgFilename stringByDeletingPathExtension]]
NSString* pathThumb = [documentPath stringByAppendingPathComponent:filenameThumb];
CGImageRef imageRefThumb = [asset thumbnail];
UIImage *imageThumb = [UIImage imageWithCGImage:imageRefThumb];
NSData *imageDataThumb = UIImagePNGRepresentation(imageThumb);
[imageDataThumb writeToFile:pathThumb atomically:YES];
}
}
I was using ELCImagePicker and was facing same problem while importing multiple photos at a time from photos library using asselts. We can not reduce time taken to import but crash issue will be resolved.
for (int j=0; j<[assetArray count]; j++)
{
#autoreleasepool // This is compiler level feature so will only work on xcode 4.1 or above
{
ALAsset *assest = [assetArray objectAtIndex:j];
CGImageRef imageRef = assest.defaultRepresentation.fullResolutionImage;
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:documentsPath atomically:YES];
}
}
If possible try to store only AssetURL in assetArray instead of whole ALAsset object and create ALAsset at a time from url so may be it helps to reduce memory consumption. In such case you will need to use blocks as
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
CGImageRef iref = [[myasset defaultRepresentation] fullResolutionImage];
if (iref) //You have image so use it
{
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Can't get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:imageURL resultBlock:resultblock failureBlock:failureblock];

uiimagepickercontroller - get the name of the image selected from photo library

I am trying to upload the image from my iPhone/iPod touch to my online repository, I have successfully picked the image from Photo Album but i am facing one problem i want to know the name of the image such as image1.jpg or some thing like that. How i would know the name of the picked image.
Instead of using the usual image picker method (UIImage*)[info valueForKey:UIImagePickerOriginalImage] which gives you the selected image as an instance of UIImage, you can use the AssetsLibrary.framework and export the actual source file (including format, name and all metadata). This also has the advantage of the original file format (png or jpg) being preserved.
#import <AssetsLibrary/AssetsLibrary.h>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissPicker];
// try to get media resource (in case of a video)
NSURL *resourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
if(resourceURL) {
// it's a video: handle import
[self doSomethingWith:resourceURL];
} else {
// it's a photo
resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary *assetLibrary = [ALAssetsLibrary new];
[assetLibrary assetForURL:resourceURL
resultBlock:^(ALAsset *asset) {
// get data
ALAssetRepresentation *assetRep = [asset defaultRepresentation];
CGImageRef cgImg = [assetRep fullResolutionImage];
NSString *filename = [assetRep filename];
UIImage *img = [UIImage imageWithCGImage:cgImg];
NSData *data = UIImagePNGRepresentation(img);
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSURL *tempFileURL = [NSURL fileURLWithPath:[cacheDir stringByAppendingPathComponent:filename]];
BOOL result = [data writeToFile:tempFileURL.path atomically:YES];
if(result) {
// handle import
[self doSomethingWith:resourceURL];
// remove temp file
result = [[NSFileManager defaultManager] removeItemAtURL:tempFileURL error:nil];
if(!result) { NSLog(#"Error removing temp file %#", tempFileURL); }
}
}
failureBlock:^(NSError *error) {
NSLog(#"%#", error);
}];
return;
}
}
I guess knowing the exact image name would not be an issue rather getting a unique name for the picked image would solve your purpose so that you can upload the image on server and track it via its name. May be this can help you
NSMutableString *imageName = [[[NSMutableString alloc] initWithCapacity:0] autorelease];
CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
if (theUUID) {
[imageName appendString:NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID))];
CFRelease(theUUID);
}
[imageName appendString:#".png"];
After you pick the image from Picker you can generate a unique name and assign it to the Picked image.
Cheers

iPhone : creating Texture2D much slower when image loaded from file in app's Documents, why?

Slower than what? slower than creating the same textures from an image loaded from the app bundle.
How much slower ? 80 times slower on iPhone, similar ratio (but faster overall) on Mac.
My example below shows loading an image with imageNamed: ; creating textures from the first image ; saving image to a file in the app's Documents directory ; loading an image from that file ; creating textures from the second image.
Images are 640x640 png, 100 textures 64x64 are created in each case.
Creation times are 0.51 s vs. 41.3 s.
Can anyone explain this huge difference, and point me to ways and means of speeding up the second case, to make it as fast as the first, if possible ?
Rudif
#import "Texture2D.h"
#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
#define END_TIMER NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; NSLog(#"Time = %f", stop-start);
#interface UIImage (CS_Extensions)
-(UIImage *) imageAtRect:(CGRect)rect;
+(NSString *) documentsDirectory;
+(void) saveImage:(UIImage *)image toDocumentsFile:(NSString *)filename;
+(UIImage *) imageFromDocumentsFile:(NSString *)filename;
+(BOOL) documentsFileExists:(NSString *)filename;
+(void) createTexturesFromImage:(UIImage *)image640x640 texture:(Texture2D **)texture;
#end;
#implementation UIImage (MiscExt)
-(UIImage *)imageAtRect:(CGRect)rect {
CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
UIImage* subImage = [UIImage imageWithCGImage: imageRef];
CGImageRelease(imageRef);
return subImage;
}
+(NSString *) documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
+(UIImage *) imageFromDocumentsFile:(NSString *)filename {
// NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
UIImage *image = [[UIImage alloc] initWithData:data];
return image;
}
+(void) saveImage:(UIImage *)image toDocumentsFile:(NSString *)filename {
if (image != nil) { // save to local file
// NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
//You can write an NSData to the fs w/ a method on NSData.
//If you have a UIImage, you can do UIImageJPEGRepresentation() or UIImagePNGRepresentation to get data.
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
// Check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL ok = [fileManager fileExistsAtPath:path];
if (ok) {
NSLog(#"%s : written file %#", __FUNCTION__, path);
}
else {
NSLog(#"%s : failed to write file %#", __FUNCTION__, path);
}
}
}
+(BOOL) documentsFileExists:(NSString *)filename {
NSString *documentsDirectory = [self documentsDirectory];
NSString *path = [documentsDirectory stringByAppendingPathComponent:filename];
NSLog(#"%s : path %#", __FUNCTION__, path);
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path];
return exists;
}
+(void) createTexturesFromImage:(UIImage *)image640x640 texture:(Texture2D **)texture {
NSLog(#"%s -> ", __FUNCTION__);
START_TIMER;
for (int x = 0; x < 9; ++x) {
for (int y = 0; y < 9; ++y) {
UIImage *ulCorner = [image640x640 imageAtRect:CGRectMake(x*64,y*64,64,64)];
texture[y*10+x] = [[Texture2D alloc] initWithImage:ulCorner];
}
}
END_TIMER;
NSLog(#"%s <- ", __FUNCTION__);
}
#end
-(void) test {
Texture2D *texture1[100];
Texture2D *texture2[100];
// compare texture creation from a bundled file vs Documents file
{
UIImage *imageBundled = [UIImage imageNamed:#"bivio-640x640.png"];
[UIImage createTexturesFromImage:imageBundled texture:texture1];
[UIImage saveImage:imageBundled toDocumentsFile:#"docfile.png"];
BOOL ok = [UIImage documentsFileExists:#"docfile.png"];
UIImage *imageFromFile = [UIImage imageFromDocumentsFile:#"docfile.png"];
[UIImage createTexturesFromImage:imageFromFile texture:texture2];
}
}
When you built your project, XCode optimises PNGs that you put in resources.
This article explains it in details: http://iphonedevelopment.blogspot.com/2008/10/iphone-optimized-pngs.html