Convert Uiimage to Nsdata and Convert Back to Uiimage in Swift

Convert UIImage to NSData and convert back to UIImage in Swift?

UIImage(data:imageData,scale:1.0) presuming the image's scale is 1.

In swift 4.2, use below code for get Data().

image.pngData()

convert UIImage to NSData and back to UIImage

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

UIImage to NSData for Core Data in Swift 3.0

Try this:

if let img = UIImage(named: "hallo.png") {
let data = UIImagePNGRepresentation(img) as NSData?
}

Convert UIImage to NSData without using UIImagePngrepresentation or UIImageJpegRepresentation

H Bastan,

Based on your comment:

...I want to save the captured image return by device camera, through UIImagepicker delegate method in document directory...

It looks like your real goal is to save the image with EXIF data to the documents directory and not specifically getting the UIImage as an NSData object with the EXIF data. In that case, you can do the following in your implementation of imagePickerController:didFinishPickingMediaWithInfo:

// Get your image.
UIImage *capturedImage = [info objectForKey:UIImagePickerControllerOriginalImage];

// Get your metadata (includes the EXIF data).
NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];

// Create your file URL.
NSFileManager *defaultManager = [NSFileManager defaultManager];
NSURL *docsURL = [[defaultManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
NSURL *outputURL = [docsURL URLByAppendingPathComponent:@"imageWithEXIFData.jpg"];

// Set your compression quuality (0.0 to 1.0).
NSMutableDictionary *mutableMetadata = [metadata mutableCopy];
[mutableMetadata setObject:@(1.0) forKey:(__bridge NSString *)kCGImageDestinationLossyCompressionQuality];

// Create an image destination.
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((__bridge CFURLRef)outputURL, kUTTypeJPEG , 1, NULL);
if (imageDestination == NULL ) {

// Handle failure.
NSLog(@"Error -> failed to create image destination.");
return;
}

// Add your image to the destination.
CGImageDestinationAddImage(imageDestination, capturedImage.CGImage, (__bridge CFDictionaryRef)mutableMetadata);

// Finalize the destination.
if (CGImageDestinationFinalize(imageDestination) == NO) {

// Handle failure.
NSLog(@"Error -> failed to finalize the image.");
}

CFRelease(imageDestination);

From my tests the execution time was about the same or faster than doing:

NSData *data = UIImageJPEGRepresentation(capturedImage, 1.0);
[data writeToURL:outputURL atomically:YES];

...and you get to keep the EXIF data!

You could also dispatch it to a background queue if you want to make sure your UI stays responsive:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

// Do the image saving here...
});

Important Note: You will need to add the ImageIO.framework and the MobileCoreServices.framework to your target's build phases and import them in the class where you do the image saving:

#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>

Other notes
It is my understanding that in this case we're not creating a generation loss when saving the image as proposed in the example. We are using UIImage's CGImage property and as the documentation states:

The underlying Quartz image data

Converting UIImage to NSData and NSData to NSString for posting images to a server

After Long time I post my answer here.

Option 1 : Image to server and Image from Server

When we send image to server(UIImage-NSData-NSString), we need to use below coding

NSData *postData = UIImageJPEGRepresentation(myImage, 1.0);
NSString *strEncoded = [postData base64EncodedStringWithOptions:0];

When we get the image from server(NSString-NSData-UIImage),we need to use below coding

NSData *getData  = [[NSData alloc] initWithBase64EncodedString:strEncodedFromServer options:0];
UIImage *image = [UIImage imageWithData:getData];

Option 2 : Simple String Encode,Decode Conversion

NSString *strName = @"iOS";
NSData *dataEncoded = [strName dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedString = [dataEncoded base64EncodedStringWithOptions:0];
NSLog(@"The Encoded String is - %@", base64EncodedString);

NSData *dataDecoded = [[NSData alloc] initWithBase64EncodedString:base64EncodedString options:0];
NSString *strDecoded = [[NSString alloc] initWithData:dataDecoded encoding:NSUTF8StringEncoding];
NSLog(@"The DeCoded String is - %@", strDecoded);

Output Screenshot is

Sample Image

Option 3 : When we need to encode and decode the dictionary

NSDictionary *dictEncoded = @{
@"OS":@"iOS",
@"Mobile":@"iPhone",
@"Version":@"iOS10"
};

NSData *dataDictEncode = [NSJSONSerialization dataWithJSONObject:dictEncoded options:(NSJSONWritingOptions) 0 error:nil];
NSString *strBase64Encode = [dataDictEncode base64EncodedStringWithOptions:0];
NSLog(@"The encoded dictionary is - %@", strBase64Encode);

NSData *dataDictDecode = [[NSData alloc] initWithBase64EncodedString:strBase64Encode options:0];
NSDictionary *dictDecoded = [NSJSONSerialization JSONObjectWithData:dataDictDecode options:NSJSONReadingMutableContainers error:nil];
NSLog(@"The decoded dictionary is - %@", dictDecoded);

Output result is

Sample Image

Convert UIImage to NSData and save with core data

You can convert a UIImage to NSData like this:

If PNG image

UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];

If JPG image

UIImage *image = [UIImage imageNamed:@"imageName.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

You can store it in CoreData like so (this is one possible useful solution):

[newManagedObject setValue:imageData forKey:@"image"];

You can load the data from CoreData like this:

NSManagedObject *selectedObject = [[self yourFetchCOntroller] objectAtIndexPath:indexPath];
UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"image"]];

// Set the image to your image view
yourimageView.image = image;


Related Topics



Leave a reply



Submit