I'm trying to save a UIIMage and then retrieve it and display it. I've been successful by saving an image in the bundle, retrieving it from there and displaying. My problem comes from when I try to save an image to disk (converting it to NSData), then retrieving it. I convert the image to NSData like so...

NSData* topImageData = UIImageJPEGRepresentation(topImage, 1.0);

then I write it to disk like so...

[topImageData writeToFile:topPathToFile atomically:NO];

then I tried to retrieve it like so...

topSubView.image = [[UIImage alloc] initWithContentsOfFile:topPathToFile];

which returns no image (the size is zero). so then I tried...

NSData *data = [[NSData alloc] initWithContentsOfFile:topPathToFile];
topSubView.image = [[UIImage alloc] initWithData:data];

to no avail. When I step through the debugger I do see that data contains the correct number of bytes but I'm confused as to why my image is not being created. Am I missing a step? Do I need to do something with NSData before converting to an image?


Try this code. This worked for me.

Saving the data.

create path to save the image.

let libraryDirectory = NSSearchPathForDirectoriesInDomains(.libraryDirectory,
                                                               .userDomainMask,
                                                               true)[0]
let libraryURL = URL(fileURLWithPath: libraryDirectory, isDirectory: true)
let fileURL = libraryURL.appendingPathComponent("image.data")

convert the image to a Data object and save it to the file.

let data = UIImageJPEGRepresentation(myImage, 1.0)
try? data?.write(to: fileURL)

retrieving the saved image

let newImage = UIImage(contentsOfFile: fileURL.relativePath)

Create an imageview and load it with the retrieved image.

let imageView = UIImageView(image: newImage)
self.view.addSubview(imageView)

You should be able to use class methods of UIImage

[UIImage imageWithContentsOfFile:topPathToFile]; 

OR

[UIImage imageWithData:data];

Did that not work?

Hope this helps!


Just in case this helps someone, from iOS6 we have the imageWithData:scale method. To get an UIImage with the right scale from an NSData object, use that method, declaring the scale you use to store the original image. For example:

CGFloat screenScale = [[UIScreen mainScreen] scale];
UIImage *image = [UIImage imageWithData:myimage scale:screenScale];

Here, myimage is the NSData object where you stored the original image. In the example, I used the scale of the screen. If you use another scale for the original image, use that value instead.