Save UIImage Object as a PNG or JPEG File
In an earlier post on saving images from the camera to the Photo Album, a question was posed asking how to save the image to another directory other than the Photo Album. Let’s walk through one way to write a UIImage object, from the camera or otherwise, as a PNG or JPG file into the Documents directory.
Get UIImage Data as PNG or JPEG
UIKit includes two C functions, UIImageJPEGRepresentation and UIImagePNGRepresentation which will return an NSData object that represents an image in JPEG or PNG format, respectively. With this information in hand, you can then use the writeToFile method of the NSData object to write the image data to a specified path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Create paths to output images NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"]; NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"]; // Write a UIImage to JPEG with minimum compression (best quality) // The value 'image' must be a UIImage object // The value '1.0' represents image compression quality as value from 0.0 to 1.0 [UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES]; // Write image to PNG [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES]; // Let's check to see if files were successfully written... // Create file manager NSError *error; NSFileManager *fileMgr = [NSFileManager defaultManager]; // Point to Document directory NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; // Write out the contents of home directory to console NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
Important note, on lines 6 and 9, the value image must be a UIImage object.
I’ve changed the example from the original post that wrote a UIImage from the camera to the Photo Album, to write instead to the test files shown above. You can download the source code for the application here: Write UIImage Object as a PNG or JPEG File.
Simulator Not Supported
One last note, this application will only run on an actual device as the simulator does not have camera support.