Unrecognised selector error when adding UIImage to array - ios

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.

Related

How to add images in Array ios?

below image After editing the image when i click the share/save button how add images in array. i should be display in tableview and it have save locally.
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);
Add imageData to array:
[self.arr addObject:imageData];
Load images from NSData:
UIImage *img = [UIImage imageWithData:[self.arr objectAtIndex:0]];
Do not store images into an array or a dictionary, unless you want to create a cache, but caches should evict their contents in a future.
You are working on a mobile device that even if is powerful it doesn't has the same hardware of your Mac.
Memory is a limited resource and should be managed with judgment.
If you want to cache temporary those images for performance reason, you can use NSCache, basically is works like mutable dictionary but it is thread safe.
If you want to save them locally it's fine but just keep the path to them in the the array.
- (NSString*) getDocumentsPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths[0]; //Get the document directory
return documentsPath;
}
- (NSString*) writePNGImage: (UIImage*) image withName: (NSString*) imageName {
NSString *filePath = [[self getDocumentsPath] stringByAppendingPathComponent:imageName]; // Add file name
NSData *pngData = UIImagePNGRepresentation(image);
BOOL saved = [pngData writeToFile:filePath atomically:YES]; //Write the file
if (saved) {
return filePath;
}
return nil;
}
- (UIImage*) readImageAtPath:(NSString*) path {
NSData *pngData = [NSData dataWithContentsOfFile:path];
UIImage *image = [UIImage imageWithData:pngData];
return image;
}

reading and caching images from a server

I am using a method to retrieve the images as a property:
NSData *data = [[NSData alloc] initWithBase64EncodedString:spot.ImageName options:0];
UIImage *image = [UIImage imageWithData:data];
But now I need to retrieve the images from a server "http://IP/MyService/images/1.png" and cash them to my service.
To save the UIImage on file system:
NSString *documentsDirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *imagePath = [documentsDirPath stringByAppendingPathComponent:#"myfile.png"];
NSData *binaryImageData = UIImagePNGRepresentation(imageToSave);
[binaryImageData writeToFile:imagePath atomically:YES];
To retrieve the UIImage on file system:
UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];

How to create NSData from a string and an image together and decompile this NSData to a string and an image before

I've got an problem with it,Can you help me! Thank you so much!
NSString *mystring;
UIImage *image;
NSData *data = ... include data of string and image and can decompile to them like before
You can do in following manner
NSString *aStrImageName = [NSString stringWithFormat:#"splash_ipad.png"];
UIImage *aImg = [UIImage imageNamed:aStrImageName];
NSDictionary *aDictData = [NSDictionary dictionaryWithObjectsAndKeys:aStrImageName,#"ImageName",aImg,#"Image", nil];
NSData *aObjData = [NSKeyedArchiver archivedDataWithRootObject:aDictData];
NSDictionary *aDictBack = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:aObjData];
NSString *aStrImageNameBack = [aDictBack valueForKey:#"ImageName"];
UIImage *aImgBack = [aDictBack objectForKey:#"Image"];

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];
});
});
}

Convert UIImage to NSData and save with core data

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];

Resources