Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert UIImage to NSData and back to UIImage

I have to populate table cell from database and images are on device. I've to store that image in imageDataObject, how to convert that UIImage to NSData. Please suggest, I tried many solution but it's not converting back that NSData to UIImage.

    cell.textLabel.text = [[offlineImageListArray objectAtIndex:indexPath.row] imageName];
    UIImage *thumbnail = [self retrieveImageFromDevice:[[offlineImageListArray objectAtIndex:indexPath.row] imageName]];
    NSData* data = ??????????;
    ImageData *imageDataObject = [[ImageData alloc] initWithImageId:[[offlineImageListArray objectAtIndex:indexPath.row]imageId] 
    imageName:[[offlineImageListArray objectAtIndex:indexPath.row] imageName] imageData:data];
    [imagesArray addObject:imageDataObject];
like image 545
user2769614 Avatar asked Nov 16 '13 00:11

user2769614


People also ask

What is the difference between UIImage and UIImageView?

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

What is UIImage?

An object that manages image data in your app.

How do I save an image in Coredata?

Creating the Model In that entity , create one attribute . Name it img and make sure the attribute type is Binary Data, then click on the img attribute and go to Data Model Inspector. Check the box Allows External Storage. By checking this box, Core Data saves a reference to the data which will make for faster access.


2 Answers

in Swift version:

    let imageData = UIImagePNGRepresentation(image!)!
    let imageFromData = UIImage(data: imageData)
like image 88
Bilal Arslan Avatar answered Sep 17 '22 06:09

Bilal Arslan


To convert UIImage to NSData, use either UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality) or UIImagePNGRepresentation(UIImage *image)

To convert NSData to UIImage, use [UIImage imageWithData:imageData]

So your example could look like this:

cell.textLabel.text = [[offlineImageListArray objectAtIndex:indexPath.row] imageName];
UIImage *thumbnail = [self retrieveImageFromDevice:[[offlineImageListArray objectAtIndex:indexPath.row] imageName]];
NSData* data = UIImagePNGRepresentation(thumbnail);
ImageData *imageDataObject = [[ImageData alloc] initWithImageId:[[offlineImageListArray objectAtIndex:indexPath.row]imageId] imageName:[[offlineImageListArray objectAtIndex:indexPath.row] imageName] imageData:data];
[imagesArray addObject:imageDataObject];

References: https://developer.apple.com/LIBRARY/IOS/documentation/UIKit/Reference/UIKitFunctionReference/Reference/reference.html https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html

like image 22
James Glenn Avatar answered Sep 20 '22 06:09

James Glenn