Reading UIImage from Document folder - iphone

I need to read the image from document folder and prepare UIImage out of that. but when I call this function everytime memory get increasing and for large scale image this scale is large. following is same code
-(UIImage*) GetSavedImageWithName:(NSString*) aFileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableString* str = [[NSMutableString alloc] initWithCapacity:300];
[str appendString:documentsDirectory];
[str appendString:#"/"];
[str appendString:aFileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:str];
NSData *dataToWrite = nil;
UIImage* image = nil;
if(!success)
{
}
else
{
dataToWrite = [[NSData alloc] initWithContentsOfFile:str];
image = [UIImage imageWithData:dataToWrite]; YES;
}
if(dataToWrite)
{
[dataToWrite release];
dataToWrite = nil;
}
if(str)
{
[str release];
str = nil;
}
if(fileManager)
{
[fileManager release];
fileManager = nil;
}
return image;
}
Calling this way
[self SetFrontViewImage:[self GetSavedImageWithName:#"Edited"]];
I am not able to find where it is getting leak.
Thanks,
Sagar

It's consuming more memory because you're reading file-converting it to data-converting it to image and again using class method.
So instead use following way:
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:str];
UIImage* image = nil;
if(!success)
{
return nil;
}
else
{
image = [[UIImage alloc] initWithContentsOfFile:str]; YES;
}
return [image autorelease];
}
And don't release your file manager object. It is an auto release object.

Because the returned UIImage is an autorelease object. It means the run loop will release these autorelease objects later. Before it release those autorelease objects, the memory space will grow up, especially when loading images with loop or a work thread.

Related

AVFoundation framework takes delay to create thumbnails

I am using AVFoundation framework in my iPad app to record videos.When recording of a video is completed, I create a thumbnail image for same video using AVFoundation.But if I record two videos without much time delay in between then thumbnail is not created properly.Clearly it's taking some delay.How to avoid that or at least how can I know when the thumbnail of previous video has got created completely so that I can show some 'Wait' symbol to the user for that time period?
Please help as I am having no clue to resolve the issue.
//delegate method which gets called when recording ends.
//Here I create the thumb and store it in self.thumb
-(void)recorder:(AVCamRecorder *)recorder recordingDidFinishToOutputFileURL:(NSURL *)outputFileURL error:(NSError *)error
{
self.thumb=nil;
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:outputFileURL options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
[asset release];
CMTime thumbTime = CMTimeMakeWithSeconds(0,1);
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result != AVAssetImageGeneratorSucceeded) {
NSLog(#"couldn't generate thumbnail, error:%#", error);
}
self.thumb=[UIImage imageWithCGImage:im];
[generator release];
};
CGSize maxSize = CGSizeMake(320, 180);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[[UIApplication sharedApplication] endBackgroundTask:[self backgroundRecordingID]];
}
if ([[self delegate] respondsToSelector:#selector(captureManagerRecordingFinished:)]) {
[[self delegate] captureManagerRecordingFinished:self];
}
}
[self copyFileToDocuments:outputFileURL];
}
//Save video and thumbnail to documents
- (void) copyFileToDocuments:(NSURL *)fileURL
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd_HH-mm-ss"];
NSString *destinationPath = [documentsDirectory stringByAppendingFormat:#"/output_%#.mov", [dateFormatter stringFromDate:[NSDate date]]];
[dateFormatter release];
NSError *error;
if (![[NSFileManager defaultManager] copyItemAtURL:fileURL toURL:[NSURL fileURLWithPath:destinationPath] error:&error]) {
if ([[self delegate] respondsToSelector:#selector(captureManager:didFailWithError:)]) {
[[self delegate] captureManager:self didFailWithError:error];
}
}
else
{
destinationPath=[[destinationPath lastPathComponent]stringByDeletingPathExtension];
[self saveImage:self.thumb withName:destinationPath];
}
}
//Method Where I save self.thumb in app documents
-(void) saveImage:(UIImage*)image withName:(NSString*)fileName
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Save Image
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",fileName]];
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
}
Above is my code.
But self.thumb is not getting properly saved if I don't give delay in two recordings.
I used a different method.When user clicks 'Record' I first click a photo from camera and then start recording the video.Later I use the same photo as a thumbnail.
I know this is not the best approach but the best thing is its working ;)
Hope this helps someone with the same problem.

How can I use iCloud to synchronize a .zip file between my apps?

Is it possible to upload a .zip file to iCloud, and then have it be synchronized across all of a user's iOS devices?
If so, how would I go about doing this?
If there is any File size limit, then also mention max. file size allowed.
This is how I synchronized zip files with iCloud .
Steps:
1) http://transoceanic.blogspot.in/2011/07/compressuncompress-files-on.html
. Refer this link to download zip api which is having code for zipping and unzipping folder.
2) Now all you need to play with NSData.
3) "MyDocument.h" file
#import <UIKit/UIKit.h>
#interface MyDocument : UIDocument
#property (strong) NSData *zipDataContent;
#end
4)
#import "MyDocument.h"
#implementation MyDocument
#synthesize zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
self.zipDataContent = [[NSData alloc] initWithBytes:[contents bytes] length:[contents length]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return self.zipDataContent;
}
#end
5) Now somewhere in your app you need to zip folder and sync with icloud.
-(BOOL)zipFolder:(NSString *)toCompress zipFilePath:(NSString *)zipFilePath
{
BOOL isDir=NO;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
NSArray *subpaths;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:pathToCompress];
} else if ([fileManager fileExistsAtPath:pathToCompress]) {
subpaths = [NSArray arrayWithObject:pathToCompress];
}
zipFilePath = [documentsDirectory stringByAppendingPathComponent:zipFilePath];
//NSLog(#"%#",zipFilePath);
ZipArchive *za = [[ZipArchive alloc] init];
[za CreateZipFile2:zipFilePath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[za addFileToZip:fullPath newname:path];
}
}
} else {
[za addFileToZip:pathToCompress newname:toCompress];
}
BOOL successCompressing = [za CloseZipFile2];
if(successCompressing)
return YES;
else
return NO;
}
-(IBAction) iCloudSyncing:(id)sender
{
//***** PARSE ZIP FILE : Pictures *****
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if([self zipFolder:#"Pictures" zipFilePath:#"iCloudPictures"])
NSLog(#"Picture Folder is zipped");
ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:#"iCloudPictures.zip"];
mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:#"iCloudPictures"];
NSURL *u = [[NSURL alloc] initFileURLWithPath:zipFilePath];
NSData *data = [[NSData alloc] initWithContentsOfURL:u];
// NSLog(#"%# %#",zipFilePath,data);
mydoc.zipDataContent = data;
[mydoc saveToURL:[mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"PictureZip: Synced with icloud");
}
else
NSLog(#"PictureZip: Syncing FAILED with icloud");
}];
}
6) You can unzip data received from iCloud like this.
- (void)loadData:(NSMetadataQuery *)queryData {
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:#"iCloudPictures"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"Pictures : Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *zipFolder = [documentsDirectory stringByAppendingPathComponent:#"Pics.zip"];
[[NSFileManager defaultManager] createFileAtPath:zipFolder contents:file attributes:nil];
//NSLog(#"zipFilePath : %#",zipFolder);
NSString *outputFolder = [documentsDirectory stringByAppendingPathComponent:#"Pictures"];//iCloudPics
ZipArchive* za = [[ZipArchive alloc] init];
if( [za UnzipOpenFile: zipFolder] ) {
if( [za UnzipFileTo:outputFolder overWrite:YES] != NO ) {
NSLog(#"Pics : unzip successfully");
}
[za UnzipCloseFile];
}
[za release];
NSError *err;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:outputFolder error:&err];
if (files == nil) {
NSLog(#"EMPTY Folder: %#",outputFolder);
}
// Add all sbzs to a list
for (NSString *file in files) {
//if ([file.pathExtension compare:#".jpeg" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
NSLog(#" Pictures %#",file);
// NSFileManager *fm = [NSFileManager defaultManager];
// NSDictionary *attributes = [fm fileAttributesAtPath:[NSString stringWithFormat:#"%#/%#",documentsDirectory,file] traverseLink:NO];
//
// NSNumber* fileSize = [attributes objectForKey:NSFileSize];
// int e = [fileSize intValue]; //Size in bytes
// NSLog(#"%#__%d",file,e);
}
}
else
{
NSLog(#"Pictures : failed to open from iCloud");
[self hideProcessingView];
}
}];
}
}
}
In order to enabling Document storage in iCloud your "document" needs to be encapsulated in a UIDocument object.
Because UIDocument links to a file URL, you can easily create a UIDocument pointing to file://myzipfile.zip and then upload a zip document to iCloud.
I hope this helps
Probably this tutorial can help you more:
http://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1

Trying to save images in ipad app bundle from photo library

-(IBAction)saveImage{
NSMutableArray *dictWords= [[NSMutableArray alloc]initWithObjects:#"TIGER",#"CAT", #"ROSE", #"ELEPHANT",#"MOUSE IS LOOKING FOR THE CHEESE",#"KITE",#"CAR",#"AEROPLANE",#"MANGO",#"FRUITS ARE FALLING FROM THE TREE",#"MOUNTAIN",#"BIRDS ARE FLYING",#"IGLOO",#"THIS HOUSE IS BUILT OF WOODS",#"BANANA",#"RAINBOW",#"TRAIN",#"DADDY DRINKS JUICE",#"UMBRELLA",#"GOAT",#"CAT JUMPS HIGH",#"DOG RUNS FAST",#"BUS",#"GIRL IS CRYING",#"STARS",#"DOLPHIN",#"BOYS ARE PLAYING FOOTBALL",#"GLASS IS FULL OF WATER",#"SHIP",#"SNOWFALL",#"GHOST",#"RABBIT",#"WATERMELON",#"SPIDERMAN",#"DINOSAUR",#"MICKEY MOUSE",#"MONKEY IS SITTING ON A TREE",#"PEACOCK",#"LIGHTNING",#"HEN LAYS EGGS",nil];
NSString *path=[[NSBundle mainBundle] pathForResource:[youSaid text] ofType:#"png" inDirectory:#"Image"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0 ; i<[assets count]; i++) {
if (i<[dictWords count]) {
[dict setObject:[[[assets objectAtIndex:i] defaultRepresentation] url] forKey:[NSString stringWithFormat:#"%#",[dictWords objectAtIndex:i]]];
NSLog(#"diccount:%d",[dict count]);
}
}
NSURL *imageurl = [dict objectForKey:[youSaid text]];
//NSLog(#"text:%#",[youSaid text]);
//Getting asset from url
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
//Setting asset image to image view according to the image url
[imageview setImage:[UIImage imageWithCGImage:iref]];
youSaid.text = [NSString stringWithFormat:#"%#",imageurl];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Error, cant get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageurl resultBlock:resultblock failureBlock:failureblock];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", youSaid.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
#end
This is the following code i wrote but i am not able to save images.i am only able to sane an image known as NULL.png .please suggest the changes to save all the pics in my library to bundle.
Thanks,
Christy
Sample Code
- (void) openPhotoLibrary {
NSLog(#"openPhotolibrary");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
if (self.picker != nil) {
NSLog(#"releasing self.picker...");
[self.picker release];
}
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//self.picker.allowsImageEditing = YES;
[self.picker presentModalViewController:self.picker animated:YES];
self.picker.delegate = self;
[[[CCDirector sharedDirector] openGLView] addSubview:self.picker.view];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker {
NSLog(#"imagePickerControllerDidCancel");
// hide the self.picker if user cancels picking an image.
[currentPicker dismissModalViewControllerAnimated:YES];
self.picker.view.hidden = YES;
[self.picker.view removeFromSuperview];
}
- (void)imagePickerController:(UIImagePickerController *)currentPicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self saveImage:image withImageName:#"myPhoto"];
}
//saving an image
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
This code its working for me try it may be its helps you
-(IBAction)PhotoLibraryButtonClicked:(id)sender{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
}
else{
[self displaysorceError];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//[self.popoverrcontroller dismissPopoverAnimated:true];
//[popoverrcontroller release];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// UIImage *rote = [image rotateInDegrees:219.0f];
img.image = image;
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//not available vidio
}
}
-(IBAction)saveImageIn:(id)sender{
NSData *imageData = UIImagePNGRepresentation(img.image);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.png",img.image]];
[fileMan createFileAtPath:fullPathToFile contents:imageData attributes:nil];
UIAlertView *alt = [[UIAlertView alloc]
initWithTitle:#"Thank You"
message:#"Image Save In Directory"
delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alt show];
[alt release];
}
thank you..:)Neet

iPhone: Memory leak when using NSOperationQueue

I'm sitting here for at least half an hour to find a memory leak in my code.
I just replaced an synchronous call to a (touch) method with an asynchronous one using NSOperationQueue.
The Leak Inspector reports a memory leak after I did the change to the code.
What's wrong with the version using NSOperationQueue?
Version without a MemoryLeak
-(NSData *)dataForKey:(NSString*)ressourceId_
{
NSString *cacheKey = [self cacheKeyForRessource:ressourceId_]; // returns an autoreleased NSString*
NSString *path = [self cachePathForKey:cacheKey]; // returns an autoreleased NSString*
NSData *data = [[self memoryCache] objectForKey:cacheKey];
if (!data)
{
data = [self loadData:path]; // returns an autoreleased NSData*
if (data)
{
[[self memoryCache] setObject:data forKey:cacheKey];
}
}
[[self touch:path];
return data;
}
Version with a MemoryLeak (I do not see any)
-(NSData *)dataForKey:(NSString*)ressourceId_
{
NSString *cacheKey = [self cacheKeyForRessource:ressourceId_]; // returns an autoreleased NSString*
NSString *path = [self cachePathForKey:cacheKey]; // returns an autoreleased NSString*
NSData *data = [[self memoryCache] objectForKey:cacheKey];
if (!data)
{
data = [self loadData:path]; // returns an autoreleased NSData*
if (data)
{
[[self memoryCache] setObject:data forKey:cacheKey];
}
}
NSInvocationOperation *touchOp = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(touch:) object:path];
[[self operationQueue] addOperation:touchOp];
[touchOp release];
return data;
}
And of course, the touch method does nothing special too. Just change the date of the file.
-(void)touch:(id)path_
{
NSString *path = (NSString *)path_;
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:path])
{
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate date], NSFileModificationDate, nil];
[fm setAttributes: attributes ofItemAtPath:path error:nil];
}
}

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