Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData to UIImage

Tags:

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?

like image 936
bruin Avatar asked Feb 10 '10 22:02

bruin


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 .

What is UIImage Swift?

An object that manages image data in your app.

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.

What is NSData in iOS?

A static byte buffer that bridges to Data ; use NSData when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+


1 Answers

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) 
like image 185
ArunGJ Avatar answered Sep 28 '22 11:09

ArunGJ