Save UIImage Object as a PNG or JPEG File

Thu, Mar 4

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.

Source Code

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.

31 comments

Thanks for this tip, I appreciate the source code as well!

by Poncho on Mar 4, 2010. #

Thanks.

by Suresh on Mar 8, 2010. #

Thanks very much for the tutorials! They’re very helpful. Could you go over how to load an image from this directory? I’m having trouble finding concise help on how to do that.

Thanks!
Thomas

by Thomas on Apr 15, 2010. #

Thanx alot for the code it really helps alot..

but how could i save in the photos directory of ipod ?? :(

by Ahmad Shahzad on Jul 6, 2010. #

Ahmad, you may find this post helpful: Camera Application to Take Pictures and Save Images to Photo Album

by John Muchow on Jul 6, 2010. #

Great help! Thank you for the post.

by Pepe on Nov 11, 2010. #

Thanks for the the awesome concise post.

by Tim Pickard on Nov 17, 2010. #

Thank you so much for the post! However, my photos are being saved sideways. Have you run into this issue? If so, how can it be fixed?

by Win Raguini on Dec 2, 2010. #

I appreciate your post greatly! I was wondering if you had a way to find the next sequential image to save in a directory? If I name images 001.jpg, 002.jpg, etc. is there a way to know what the next number is? I’m hoping to later load these images sequentially as a slideshow. Thanks.

by Matt Burnell on Dec 27, 2010. #

Matt, I think I’ve bumped into something similar to what you are after, however I can’t seem to put my finger on where it was and if it was Objective-C or otherwise. You may need to write a simple method to keep a counter of the most recently used number.

by John Muchow on Dec 28, 2010. #

John, Thank you for the comment. I am thinking that it might be a good idea to just store the image(s) in the photo gallery and use a dictionary object (if that’s the right terminology) to keep a reference of images and in what order they should appear. Working through a sample project to see how this might be accomplished. Thanks again.

by Matt Burnell on Dec 28, 2010. #

Yes, the Dictionary is your friend. Depending on what you need in your app, you may also consider storing various attributes that may be helpful (for example last image number used). From there, you can write the dictionary to persistent storage and read the dictionary upon startup for use in your app.

by John Muchow on Dec 28, 2010. #

John, Perfect. Thanks. I will make sure to do that.

by Matt Burnell on Dec 28, 2010. #

Hi Thanks for the code. I downloaded it and ran it on my iphone 3g. But I am getting the following error. Please help

ERROR: FigCreateCGImageFromJPEG returned -12905. Input (null) was 449733 bytes.

by rakendu on Feb 21, 2011. #

Not sure why you are getting this error, may have to do with the OS version of your device. You may want to try the Apple PhotoPicker example and see if generates a similar error:
http://developer.apple.com/library/ios/samplecode/PhotoPicker/PhotoPicker.zip

by John Muchow on Feb 22, 2011. #

very helpfull,

thanks

by daniela on Mar 10, 2011. #

Thanks !!! it works like a charm !

by Alejandro on Mar 28, 2011. #

Thanx a lot, you are awesome ;-)

by wael on May 30, 2011. #

Hello,

I am testing this project using IOS 4.3 on an iPhone 4 and after hitting the “Use” button there is a good 20 second delay before it moves back to the original screen. Can the delay be corrected or is due to the processing of the image?

Thanks for your help and thank you so much for your wonderful tutorials.

by Nick on Jul 14, 2011. #

That does seems long, however I know the delay can be pretty long for the camera to save a file.

by John Muchow on Jul 14, 2011. #

I agree that the camera takes a while to save the file but I guess my goal would be to have the code return to the main screen (in my app at least) while the file is saving. The time it takes to save isn’t an issue, the fact that the app waits for the save to take place before moving on to the next step is what is causing my current headache. Thanks for replying John, any input is highly welcome.

by Nick on Jul 14, 2011. #

Hello,

I am using a custom MainViewController to show all of my views. I have created a view for the camera controller and it seems to work fine, however I am unable to get back to my original view. I know that the camera creates it’s own view instance and I am activating it through a button in a form from another view, but after image is captured, it returns to the activate button screen that it creates. I was able to rig it up to display the original form it was on using initWithNibName but when it loads the view non of the buttons or functions work because I think it’s still outside of the MainViewController.

Is there a way to integrate this script to work inside my view controller and get rid of all of the automatically generated separate view for the image capture script? Thanks for your help.

Nick

by Nick on Jul 27, 2011. #

Hello Everyone else who is having an issue with the views. I was able to fix it by actually creating an XIB with a capture button and a back button that is activated using the initWithNibName. I removed the – (id)init and then turned the – (void)buttonPressed:(UIButton *)button in to an action called -(IBAction)buttonPressed and referenced it using a capture image in the XIB view. This way I was able to activate the image capture event while remaining in my own custom view controller. At the end of the image capture, once the “Use” button is selected, the XIB view is brought up which has a “Back” button that links back to the original form with the button that loads the CameraCaptureView.XIB view. If anyone needs help then reply to this and I’ll check back later. Thanks again for the OP, you are a life saver my friend!

Nick

by Nick on Jul 27, 2011. #

Very helpful! I use it to save the artwork of the currently playing track. And I only have 1 minor problem with it. I ask for a 300 x 300 pixel image, but get a 640 x 640 pixel image.

Here’s the code:

NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@”Documents/Artwork.png”];
UIImage *plaatje;
MPMediaItem *currentItem;
currentItem = [[MPMusicPlayerController iPodMusicPlayer] nowPlayingItem];
if (currentItem == NULL)
return @””;
else {
CGSize artworkImageViewSize = CGSizeMake(300, 300);
MPMediaItemArtwork *artwork = [currentItem valueForProperty:MPMediaItemPropertyArtwork];
if (artwork != nil) {
plaatje = [artwork imageWithSize:artworkImageViewSize];
[UIImagePNGRepresentation(plaatje) writeToFile:pngPath atomically:YES];
return pngPath;
} else {
return @””;
}
}

by Terry Vogelaar on Sep 27, 2011. #

Hi,

It sounds like I have a similar problem.
On an old device (iPod touch about 3 years old) things work fine, but on an iPhone 4 I also get a double size PNG file. Did you solve the problem?

Thanks for the reply if you have the time.

by Michel on Jan 25, 2012. #

No, I didn’t. I just display it smaller, so it doesn’t bother me anymore. But it is a bit silly that it doesn’t work.

by Terry Vogelaar on Jan 25, 2012. #

Awesome tutorial!
Works, Please make another tutorial on how to load the image from Documents! VERY MUCH appreciated!!

by Steven on Dec 4, 2011. #

Hi, Thanks for the gr8 tutorial.
My question is how to know the name of the image taken by the user using camera type source in order to write the name of the image to the document directory.
And also how can we save the image taken by the user in the documents directory?

by madhuri on Jan 22, 2012. #

Hi, I have a problem when I try to test the app on the device:

– When I look for the path to save the photo in the Documents directory, I get this path /var/mobile/Applications/9920C9E8-37E4-424C-ABA1-9F6E224594ED/Documents – this is because I’m running the app on the device, I think.

– But, when I try to write out the content of the SAME path, I get the content of the Library/ApplicationSupport/iPhoneSimulator/5.0/Applications/IDofTheApplication/Documents – as I would be running it on the iPhone Simulator.

So, I can’t know what am I saving and if it is everything ok.
Can anyone help me with this problem?

Thanks in advance.

by Daniel on Jan 27, 2012. #

Hi there I am taking a picture with the camera inside an app and then saving to my documents directory and then loading it into a UIImageView. I am trying to resize the photo down to 105 x 140 before saving it. This is the code.

[UIImageJPEGRepresentation(image, 0.1) writeToFile:pngPath atomically:YES];
CGRect rect = CGRectMake(0.0, 0.0, 105.0, 140.0);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
NSFileManager *fileMgr = [NSFileManager defaultManager];
I’m not sure if this is working or not. I don’t get any errors and the file is saved because I can load it later. Is there anyway to check to see what size it is being saved as?

by Gary Benna on Feb 22, 2012. #

“Simulator Not Supported
One last note, this application will only run on an actual device as the simulator does not have camera support.”

You can save an image in a Photos album and then pick it to simulate the camera.

Drag an image into the simulator.
Safari will open.
Click and hold on the image.
Safari will ask you if you want to save it.
Click “Save Image”

Use the appropriate source type:

UIImagePickerControllerSourceTypePhotoLibrary
UIImagePickerControllerSourceTypeCamera
UIImagePickerControllerSourceTypeSavedPhotosAlbum

by Cliff Harris on Aug 18, 2012. #