NSData to UIImage

bruin  picture bruin · Feb 10, 2010 · Viewed 59.1k times · Source

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?

Answer

ArunGJ picture ArunGJ · Apr 19, 2011

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)