Convert UIImage to NSData and save with core data - ios

I have a UIImageView whose image gets set via UIImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[picker dismissViewControllerAnimated:YES completion:nil];
self.gImage.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
}
I "attempt" to convert this image to NSData and save it with core data:
NSData *imageData = UIImagePNGRepresentation(self.gImage.image);
NSString *savedData = [[NSString alloc]initWithData:imageData encoding:NSUTF8StringEncoding];
//am is a pointer to my entities class. imageData is just a NSString attribute
am.imageData = savedData;
NSError *error;
if (![self.managedObjectContext save:&error]) {
//Handle Error
} else {
[self dismissViewControllerAnimated:YES completion:nil];
}
Then I try to load the image in a separate file:
self.cell.gImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.myEntity.imageData]]];
I cannot see why this is not working. Any help is greatly appreciated!

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;

For swift its just:
UIImage to NSData
imageData = UIImagePNGRepresentation(image)

For storing in database:::
NSInteger RandomIndex = arc4random() % 1000;
NSString *randomImageName =[NSString stringWithFormat:#"Image%i.png",RandomIndex];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:randomImageName];
if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
[[NSFileManager defaultManager] removeItemAtPath:savedImagePath error:nil];
NSLog(#"file removed from path");
}
NSLog(#"Saved Image Path : %#",savedImagePath);
NSData* imageData = UIImagePNGRepresentation (image1 );
[imageData writeToFile:savedImagePath atomically:YES];
//am is a pointer to my entities class. imageData is just a NSString attribute
am.imageData = randomImageName;
When you get that image from data base, you can write following code...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:randomImageName];
NSData *myData = [NSData dataWithContentsOfFile:savedImagePath];
UIImage *selectedImage = [UIImage imageWithData:myData];
I think it is helpful to you.

On Mac OS you can let Core Data handle this for you by ticking the Transformable box on the attribute in the model, not selecting a specific transformer, and assigning the UIImage directly to the property.
I'm not sure if it works on iOS but it might be worth a try.

To convert an image to NSData try below code...
UIImage *image = [UIImage imageNamed:#"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
let me know it is working or not..!!!
Happy Coding!!!!

Try This Code to save image data
to save:
NSManagedObjectContext *context = [self managedObjectContext];
newsObj = [NSEntityDescription insertNewObjectForEntityForName:#"Event" inManagedObjectContext:context];
NSData *imageData = UIImagePNGRepresentation(self.gImage.image);
[newsObj setValue:imageData forKey:#"imgPng"];
NSError *error;
#try{
if (managedObjectContext != nil) {
if (![managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}
}#catch (NSException *exception) {
NSLog(#"inside exception");
}
To Retrive Try this:
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity1 = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:context];
[fetchRequest setEntity:entity1];
NSError *error;
NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (array == nil) {
NSLog(#"Testing: No results found");
}else {
NSLog(#"Testing: %d Results found.", [array count]);
}
NSData * dataBytes = [[array objectAtIndex:0] imgPng];;
image = [UIImage imageWithData:dataBytes];
[fetchRequest release];
}
#catch (NSException *exception) {
NSLog(#"inside exception");
}

This code save your image data into filedata and you can use it anywhere
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image1 editingInfo:(NSDictionary *)editingInfo
{
{
CGSize destinationSize = CGSizeMake(170,170);
UIGraphicsBeginImageContext(destinationSize);
[image1 drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NsData *filedata = UIImagePNGRepresentation(newImage);
[picker dismissModalViewControllerAnimated:YES];
}
}

Here is what I have done and its working for storing to nsdata.
[productTypeSub setValue:[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]] forKey:#"imgSmall"];
and loading to image with this code
ImgProductType.image= [[UIImage alloc] initWithData:productTypeSub.imgSmall];

Related

save custom camera capture image iOS Xcode

I am new to iPhone, I want to save image into the album & I want that image path.
I did this already.
Now, I want a custom name for image & store image with that name.
I used below code but I am not getting any image into the album.
Can anybody guide me where am I wrong ?
#pragma mark - Image Picker Controller delegate methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
// Todo to use custom name comment this line.
//UIImageWriteToSavedPhotosAlbum(self.imageView.image,nil,nil,nil);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
});
}
You can Store Image with Custom name like this :
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
//save image in Document Derectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Get Path : %#",documentsDirectory);
//create Folder if Not Exist
NSError *error = nil;
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSString *customePhotoName=#"MyPhotoName";
NSString* path= [dataPath stringByAppendingString:[NSString stringWithFormat:#"/%#.png",customePhotoName]];
NSData* imageData = UIImagePNGRepresentation(chosenImage);
[imageData writeToFile:path atomically:YES];
NSLog(#"Save Image Path : %#",path);
In one of my project I did this:
let directory = "yourDirectoryName"
let fileName = "file.png"
let directoryPath = NSHomeDirectory() + "/Library/Caches/\(directory)"
do {
try NSFileManager.defaultManager().createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil)
UIImagePNGRepresentation(image)?.writeToFile(directoryPath+fileName), atomically: true)
} catch let error as NSError {}
Code works in Swift 2.3. I hope, this is what you want.
Verify if NSData and UIImage objects are proper, set "atomically" as YES, check out the below code I use:
//Save your image with a completion selector
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
//Completion selector
- (void) image: (UIImage *) image
didFinishSavingWithError: (NSError *) error
contextInfo: (void *) contextInfo
{
if(error)
{
NSLog(#"save error :%#", [error localizedDescription]);
}
else if (!error)
{
PHAsset *asset = [self fetchImageAsset];
}
}
//Fetch image based on create date or whatever naming system you follow
- (nullable PHAsset *)fetchImageAsset
{
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
PHAsset *lastAsset = [fetchResult lastObject];
return lastAsset;
}

imageView blank when set with URL?

I'm using the below to set my imageView with a url (located in path). Yes, the URL data is returned successfully, but for some reason, my imageView remains blank (just white?)
And yes, I've hooked up my imageView property... Any idea what's wrong? Should I be using a different block of code to accomplish this?
Viewcontroller.m
NSMutableDictionary *viewParamsDogs = [NSMutableDictionary new];
[viewParamsDogs setValue:#"mydogs" forKey:#"view_name"];
[DIOSView viewGet:viewParamsDogs success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.dogData = [responseObject mutableCopy];
[operation responseString];
NSDictionary *dic = [responseObject valueForKey: #"field_pet_photo_path"];
NSArray *arr = [dic valueForKey: #"und"];
NSDictionary *dic2= [arr objectAtIndex : 0];
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSLog(#"This is path %#", path);
if([path length]>0) {
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = image;
} else {
NSString *ImageURL = #"http://url.ca/paw.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.dogimageView.image = [UIImage imageWithData:imageData];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
Path:
[5111:1673330] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
)
NSLog(#"This is path %#, %#", path, NSStringFromClass(path.class)); returns:
2016-04-14 13:18:39.590 [5225:1700657] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
), __NSCFString
I recommend usage of AFNetworking https://github.com/AFNetworking/AFNetworking for all networking connect features.
Import UIImageView+AFNetworking.h at beginning of file
#import "UIImageView+AFNetworking.h"
Get path from dic2
NSString *path = dic2[#"safe_value"];
Check if path is a string
if (![path isKindOfClass:[NSString class]]) {
return;
}
Create a NSURL object from string
NSURL *imageUrl = [NSURL URLWithString:path];
Set imageUrl to UIImageView
[self.dogimageView setImageWithURL:imageUrl];
You could check the full code in my gist https://gist.github.com/MaciejGad/fa8cb80dfc73ea55edeedb75418ea2ec
Edit:
the reason of error was the path that was set as:
NSString *path = #"(
\"http://url.com/default/files/stored/1460659054.jpg\"
)";
to change to normal URL we need to trim it:
NSMutableCharacterSet *characterSetToTrim = [NSMutableCharacterSet characterSetWithCharactersInString:#"()\""];
[characterSetToTrim formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
path = [path stringByTrimmingCharactersInSet:characterSetToTrim];
after this trimming path should be http://url.com/default/files/stored/1460659054.jpg
Try like this,
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
and You can use great library SDWebImage for caching image. When image comes from server use of this library is very helpful. Hope this will work.
Update :
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
Try this. :)
Try using dataWithContentsOfURL:options:error: instead and look if there is any error message there

iOS UIImagePNGRepresentation crash due to "Memory Pressure"

I have UIImagePicker and UICollectionView in my view controller. I'am taking pictures and on 4th picture (it is also new line in collection view) application crashes due to "Memory Pressure". UIImagePicker delegate:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Do picture get here
NSError *error;
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(image);
NSNumber *imageNumber = [NSNumber numberWithInteger:[databaseManagementService selectTaskPictures].count];
NSString *imageName = [[imageNameDefault stringByAppendingString:[NSString stringWithFormat:objectFormat, imageNumber]] stringByAppendingString:extensionPNG];
// Do picture save to documents directory here
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:savedImagePath atomically:NO];
// Do UIImagePicker dismiss here
[picker dismissViewControllerAnimated:YES completion:nil];
// Do picture details save to database here
TaskManagerTaskPicture *taskPicture = [[TaskManagerTaskPicture alloc] init];
taskPicture.filename = imageName;
taskPicture.id = imageNumber;
taskPicture.title = imageName;
taskPicture.pictureID = self.taskObject.id;
taskPicture.taskID = self.taskObject.id;
taskPicture.locationID = self.taskObject.location.id;
[databaseManagementService insertTaskPictureObject:taskPicture andError:&error];
// Do task picture update here
// Do task object SELECT here
self.taskObject = [databaseManagementService selectTaskWithID:self.taskObject.id];
// Do task picture objects retreive from task object here
self.taskPictureObjects = [self.taskObject.taskPicture allObjects];
// Do collection data reload here
[self.taskPicturesCollectionView reloadData];
}
Until now I have been debuting and realized that trouble is dousing by line:
NSData *imageData = UIImagePNGRepresentation(image);
Does anyone have any idea how to fix this issue?
Can you explain better the flow of your app?
However try implementing this code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Do picture get here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSError *error;
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(image);
NSNumber *imageNumber = [NSNumber numberWithInteger:[databaseManagementService selectTaskPictures].count];
NSString *imageName = [[imageNameDefault stringByAppendingString:[NSString stringWithFormat:objectFormat, imageNumber]] stringByAppendingString:extensionPNG];
// Do picture save to documents directory here
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:savedImagePath atomically:YES];
dispatch_async(dispatch_get_main_queue(), ^{
// Do UIImagePicker dismiss here
[picker dismissViewControllerAnimated:YES completion:nil];
// Do picture details save to database here
TaskManagerTaskPicture *taskPicture = [[TaskManagerTaskPicture alloc] init];
taskPicture.filename = imageName;
taskPicture.id = imageNumber;
taskPicture.title = imageName;
taskPicture.pictureID = self.taskObject.id;
taskPicture.taskID = self.taskObject.id;
taskPicture.locationID = self.taskObject.location.id;
[databaseManagementService insertTaskPictureObject:taskPicture andError:&error];
// Do task picture update here
// Do task object SELECT here
self.taskObject = [databaseManagementService selectTaskWithID:self.taskObject.id];
// Do task picture objects retreive from task object here
self.taskPictureObjects = [self.taskObject.taskPicture allObjects];
// Do collection data reload here
[self.taskPicturesCollectionView reloadData];
});
});
}

Unrecognised selector error when adding UIImage to array

I am storing a UIImage in a NSDictionary, and then passing the NSDictionary at another place in the app. gridImages is a NSMutableArray
NSDictionary *pageDict = [pageArray objectAtIndex:0];
UIImage *pageImage = [pageDict objectForKey:#"image"];
[gridImages addObject:pageImage];
pagedict returns
{
class = is;
image = "<UIImage: 0x14e20e10>";
name = kaka;
page = 64;
}
which presumably I do
UIImage *pageImage = [pageDict objectForKey:#"image"];
However, when I try to add that UIImage to an array, I get this error:
-[UIImage stringByDeletingPathExtension]: unrecognized selector sent to instance 0x14e20e10
Any idea whats going on?
EDIT:
For the NSDictionary, I tried storing the UIImage as NSData:
NSData *imageData = UIImagePNGRepresentation(textbookImage);
[pageDict setObject:imageData forKey:#"image"];
[pageDict setObject:textbookName forKey:#"name"];
[pageDict setObject:page forKey:#"page"];
[pageDict setObject:nameOfClass forKey:#"class"];
And the parsing it like this:
NSData *imageData = [pageDict objectForKey:#"image"];
UIImage *pageImage = [UIImage imageWithData:imageData];
But it still returns the same error
You can't set UIImage into NSUserDefaults as UIImage is non-property-list object.
You better store path of image from documents directory.
This code will help.
// SET Image
NSString *strImagePath = //path of image from documents directory
NSMutableDictionary *dictOne = [NSMutableDictionary dictionaryWithCapacity:0];
[dictOne setObject:strImagePath forKey:#"image"];
[[NSUserDefaults standardUserDefaults] setObject:dictOne forKey:#"dict"];
// GET image
NSMutableDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:#"dict"];
UIImage *image = [UIImage imageWithContentsOfFile:[dict objectForKey#"image"]];
EDIT:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strImageFileName = [documentsDirectory stringByAppendingPathComponent:#"yourImageFileName"];
UIImage *image = // Your image;
NSData *dataImage = UIImageJPEGRepresentation(image, 0.5f);
/* Good image quality
NSData *dataImage = UIImagePNGRepresentation(image);
*/
[dataImage writeToFile:strImageFileName atomically:YES];
Happy coding.

AVCam Libriary capture image saving

hi I am using the AVCam Liberary for automatic image capturing.I dont want to
save the image in photo libriary I want to save the image in document directory .it saves the image but having problem when i
load this image gives access bad.
- (void) captureStillImage
{
AVCaptureConnection *stillImageConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeVideo fromConnections:[[self stillImageOutput] connections]];
if ([stillImageConnection isVideoOrientationSupported])
[stillImageConnection setVideoOrientation:orientation];
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:stillImageConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
ALAssetsLibraryWriteImageCompletionBlock completionBlock = ^(NSURL *assetURL, NSError *error) {
if (error) {
if ([[self delegate] respondsToSelector:#selector(captureManager:didFailWithError:)]) {
[[self delegate] captureManager:self didFailWithError:error];
}
}
};
if (imageDataSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
UIImage *image = [[UIImage alloc] initWithData:imageData];
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/Image.jpg", docDirectory];
NSData *imageDataToSave = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageDataToSave writeToFile:filePath atomically:YES];
//[self saveImage:image];
completionBlock:completionBlock];
[image release];
[library release];
}
else
completionBlock(nil, error);
if ([[self delegate] respondsToSelector:#selector(captureManagerStillImageCaptured:)]) {
[[self delegate] captureManagerStillImageCaptured:self];
}
}];
}
and loading the image
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/Image.jpg", docDirectory];
UIImage* loadedImage = [UIImage imageWithContentsOfFile:filePath];
[ImageView setImage:loadedImage];
when this loadedImage is assign to any UIImage
While writing the file try -
[UIImagePNGRepresentation(self.imageView.image) writeToFile:pngPath atomically:YES];

Resources