Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save a UIImage to a file?

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

like image 264
user1542660 Avatar asked Jul 21 '12 12:07

user1542660


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do I find my UIImage path?

Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.

How do you add a UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]];

What is pngData?

pngData() Returns a data object that contains the specified image in PNG format.


2 Answers

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.

like image 170
DrummerB Avatar answered Sep 21 '22 20:09

DrummerB


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) 
like image 23
NatashaTheRobot Avatar answered Sep 23 '22 20:09

NatashaTheRobot