Quantcast
Channel: How do I save a UIImage to a file? - Stack Overflow
Viewing all articles
Browse latest Browse all 10

Answer by Alex the Ukrainian for How do I save a UIImage to a file?

$
0
0

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 specNSData *imageData = UIImageJPEGRepresentation(image, 0.85f); // quality level 85%[imageData writeToFile:filePath atomically:YES];

Viewing all articles
Browse latest Browse all 10

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>