How do I save a UIImage to a file?

IphoneObjective CIosUiimage

Iphone Problem Overview


If I have a UIImage from an imagePicker, how can I save it to a subfolder in the documents directory?

Iphone Solutions


Solution 1 - Iphone

Of course you can create subfolders in the documents folder of your app. You use NSFileManager to do that.

You use UIImagePNGRepresentation to convert your image to NSData and save that to disk.

// Create path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];
 
// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

Core Data has nothing to do with saving images to disk by the way.

Solution 2 - Iphone

In Swift 3:

// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"

// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)

Solution 3 - Iphone

You have to construct a representation of your image as a particular format (say, JPEG or PNG), and then call writeToFile:atomically: on the representation:

UIImage *image = ...;
NSString  *path = ...;
[UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];

Solution 4 - Iphone

The above are useful, but they don't answer your question of how to save in a subdirectory or get the image from a UIImagePicker.

First, you must specify that your controller implements image picker's delegate, in either .m or .h code file, such as:

@interface CameraViewController () <UIImagePickerControllerDelegate>

@end

Then you implement the delegate's imagePickerController:didFinishPickingMediaWithInfo: method, which is where you can get the photograph from the image picker and save it (of course, you may have another class/object that handles the saving, but I'll just show the code inside the method):

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // get the captured image
    UIImage *image = (UIImage *)info[UIImagePickerControllerOriginalImage];
		
	
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *imageSubdirectory = [documentsDirectory stringByAppendingPathComponent:@"MySubfolderName"];

    NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.png"];

    // Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to PNG spec
    NSData *imageData = UIImagePNGRepresentation(image); 
    [imageData writeToFile:filePath atomically:YES];
}

If you want to save as JPEG image, the last 3 lines would be:

NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.jpg"];
    
// Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to JPG spec
NSData *imageData = UIImageJPEGRepresentation(image, 0.85f); // quality level 85%
[imageData writeToFile:filePath atomically:YES];

Solution 5 - Iphone

extension UIImage {
    /// Save PNG in the Documents directory
	func save(_ name: String) {
		let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
		let url = URL(fileURLWithPath: path).appendingPathComponent(name)
		try! UIImagePNGRepresentation(self)?.write(to: url)
		print("saved image at \(url)")
	}
}

// Usage: Saves file in the Documents directory
image.save("climate_model_2017.png")

Solution 6 - Iphone

NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];

where path is the name of the file you want to write it to.

Solution 7 - Iphone

First you should get the Documents directory

/* create path to cache directory inside the application's Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"fileName"];

Then you should save the photo to the file

NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
[photoData writeToFile:filePath atomically:YES];

Solution 8 - Iphone

In Swift 4.2:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try image.pngData()?.write(to: filePath, options: .atomic)
    } catch {
       // Handle the error
    }
}

Solution 9 - Iphone

In Swift 4:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try UIImagePNGRepresentation(image)?.write(to: filePath, options: .atomic)
    }
    catch {
       // Handle the error
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1542660View Question on Stackoverflow
Solution 1 - IphoneDrummerBView Answer on Stackoverflow
Solution 2 - IphoneNatashaTheRobotView Answer on Stackoverflow
Solution 3 - IphoneSergey KalinichenkoView Answer on Stackoverflow
Solution 4 - IphoneAlex the UkrainianView Answer on Stackoverflow
Solution 5 - IphoneneoneyeView Answer on Stackoverflow
Solution 6 - IphoneMaggieView Answer on Stackoverflow
Solution 7 - Iphonelu yuanView Answer on Stackoverflow
Solution 8 - IphoneTorianinView Answer on Stackoverflow
Solution 9 - IphoneSamoView Answer on Stackoverflow