Reputation: 1655
I am showing very big size images in UITableView, because of this my app is getting crashed after some time. Now i want to resize the image and save it to disk. can some one help me resizing the image from NSData/UIImage and saving saving it to the disk.
I got the code to resize the image from UIImage, so as the result i have my resized in image in UIImage object, how to save it to iphone sandbox.
Thanks,
Upvotes: 12
Views: 17181
Reputation: 6020
Here is code to save to the Documents directory on iOS that is from working code.
// Convert UIImage to JPEG
NSData *imgData = UIImageJPEGRepresentation(image, 1); // 1 is compression quality
// Identify the home directory and file name
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
// Write the file. Choose YES atomically to enforce an all or none write. Use the NO flag if partially written files are okay which can occur in cases of corruption
[imgData writeToFile:jpgPath atomically:YES];
Upvotes: 30
Reputation: 1388
NSData *imgData = UIImageJPEGRepresentation(image, 1);
CGImageSourceRef source = CGImageSourceCreateWithData((CFMutableDataRef)imgData, NULL);
NSDictionary *metadata = [(NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source,0,NULL)autorelease];
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[imageMutableData writeToFile:jpgPath atomically:YES];
It will copy your image to documents folder in sandbox with name Test.jpg
.
If you want to do it for PNG you can try UIImagePNGRepresentation(image);
Upvotes: 1
Reputation: 5421
You're asking 'how do I write a file' right?
I guess there is a touch of complication in that you probably want to write into the Library/Caches directory, so when the phone gets backed up you don't save those files.
Get the root of the app folder w/ NSHomeDirectory()
and then append Library/Caches.
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.
Upvotes: 4