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];
Related
I am developing app like camera. This is the method where I am taking photos :
-(IBAction)takephoto:(id)sender
{
tapCount += 1;
AVCaptureConnection *videoConnection = nil;
for(AVCaptureConnection *connection in StillImageOutput.connections)
{
for(AVCaptureInputPort *port in [connection inputPorts])
{
if ([[port mediaType] isEqual:AVMediaTypeVideo]){
videoConnection =connection;
break;
}
}
}
[StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error){
if (imageDataSampleBuffer!=NULL) {
NSData *imageData =[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
self.image = [ UIImage imageWithData:imageData];
}
Now I need to store the captured image in NSDocumentdirectory path and I want to show them in My collection view .
Before this I am saving the image in array and reading the image and I load them in collection view .Please help me to do this.. I don't have much knowledge about this NSDocument directory path .
The path to documents folder is
NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
To save the image you have to use
[UIImagePNGRepresentation(image) writeToFile:[appDocumentsFolder stringByAppendingPathComponent:#"/imageName.png"]; atomically:YES];
To use UICollectionView I suggest you to read same articles, like this: https://www.raywenderlich.com/136159/uicollectionview-tutorial-getting-started
I have modified your code, which will save image into Document directory.
NB : Here I assume that, you are getting the image in captureStillImageAsynchronouslyFromConnection method
My Code :
-(IBAction)takephoto:(id)sender
{
tapCount += 1;
AVCaptureConnection *videoConnection = nil;
for(AVCaptureConnection *connection in StillImageOutput.connections)
{
for(AVCaptureInputPort *port in [connection inputPorts])
{
if ([[port mediaType] isEqual:AVMediaTypeVideo]){
videoConnection =connection;
break;
}
}
}
[StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error){
if (imageDataSampleBuffer!=NULL) {
NSData *imageData =[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
self.image = [ UIImage imageWithData:imageData];
//Code to save image into Document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"SampleImage.png"];
[imageData writeToFile:savedImagePath atomically:NO];
}
}];
}
Hope it helps ...
Happy coding .
I give you detailed answer
When you want to save image into document directory
for (UIImage *img in arrImg)
{
int i=0;
NSString *pathName =nil;
NSString *fileName = [[self getCurrentDate]stringByAppendingString:[self getCurrentTime]];
fileName =[file_name stringByAppendingPathExtension:#"jpeg"];
NSArray *paths1 =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath =([paths1 count] >i) ? [paths1 objectAtIndex:i] : nil;
NSString *path = [basePath stringByAppendingPathComponent:#"Photo"];
//Get Directory in FileManager
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path])
return;
[fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
pathName =[path stringByAppendingPathComponent:file_name];
NSData *imgData =UIImageJPEGRepresentation(image, 0.4);
[imgData writeToFile:pathName atomically:YES];
NSMutableArray *arrImgpath = [[NSMutableArray alloc]init];
[arrImgPath addObject:pathName];
}
in above code arrImg is saved imges in array.
Then you need to write or call below code
-(NSString*)getCurrentTime
{
//Get Current Time for saving Images
NSString *path =nil;
NSDateFormatter *timeFormatter =[[NSDateFormatter alloc]init];
[timeFormatter setDateFormat:#"HH:mm:ss.SSS"];
NSDate *now = [[NSDate alloc]init];
NSString *str_time = [timeFormatter stringFromDate:now];
NSString *curr_time;
curr_time =[str_time stringByReplacingOccurrencesOfString:#"." withString:#""];
path = [NSString stringWithFormat:#"%#",curr_time];
return path;
}
-(NSString*)getCurrentDate
{
NSString *today =nil;
NSDateFormatter *dateFormatter1;
dateFormatter1 =[[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:#"d MMM yyyy"];
NSDate *now =[[NSDate alloc]init];
NSLocale *usLocale =[[NSLocale alloc]initWithLocaleIdentifier:#"en_US"];
[dateFormatter1 setLocale:usLocale];
NSString *str_date =[dateFormatter1 stringFromDate:now];
today=[NSString stringWithFormat:#"%#",str_date];
return today;
}
When you fetch the image from directory path
for(int j=0;j<arrImgPath.count;j++)
{
NSString *localPath=[NSString stringWithFormat:#"%#",[arrImgPath objectAtIndex:j]];
NSURL *strPathURL=[NSURL fileURLWithPath:localPath];
NSData *data = [NSData dataWithContentsOfURL:strPathURL];
UIImage *img = [[UIImage alloc] initWithData:data];
imageView.image = img;
}
I captured image using below code
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;
CALayer *viewLayer = self.vImagePreview.layer;
NSLog(#"viewLayer = %#", viewLayer);
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
[self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
NSLog(#"ERROR: trying to open camera: %#", error);
}
[session addInput:input];
[session startRunning];
_stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[_stillImageOutput setOutputSettings:outputSettings];
[session addOutput:_stillImageOutput];
when i press the button
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in _stillImageOutput.connections)
{
for (AVCaptureInputPort *port in [connection inputPorts])
{
if ([[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
NSLog(#"about to request a capture from: %#", _stillImageOutput);
[_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
if (exifAttachments)
{
// Do something with the attachments.
NSLog(#"attachements: %#", exifAttachments);
}
else
NSLog(#"no attachments");
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
self.vImage.image = image;
_vImage.hidden=YES;
UIStoryboard *storybord=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
shareViewController *shareview=[storybord instantiateViewControllerWithIdentifier:#"share"];
[self presentViewController:shareview animated:YES completion:nil];
shareview.shareimageview.image=image;
NSMutableArray *temparray = [NSMutableArray arrayWithObjects:image,nil];
NSMutableArray *newparsetile=[#[#"you"]mutableCopy];
shareview.newtile=newparsetile;
shareview.selectedimgarray=temparray;
[[NSNotificationCenter defaultCenter] postNotificationName:#"Shareimage" object:image];
}];
how to save the output image in to the device document directory,can any body help me out,answer with code is appreciated,since i am new to the ios objective c,the people who want to customize the camera like instagram can use my code it is 100% working
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"image_name”]]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
// Saving it to documents direcctory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [directoryPaths objectAtIndex:0];
NSString* filePath = [documentDirectory stringByAppendingPathComponent:#"FileName.png"];
NSData *imageData = // Some Image data;
NSURL *url = [NSURL fileURLWithPath:filePath];
if ([imageData writeToURL:url atomically:YES]) {
NSLog(#"Success");
}
else{
NSLog(#"Error");
}
You can use above code to save an image to documents directory. Instead of imagedata variable you can pass your variable.
I'm having a trouble dynamically adding UIButtons with background image as subviews to a UIScrollView. Its kind of a image gallery using UIButtons on a scrollView. I have used this method for couple of my apps, it works fine for me with the static contents.
But this time, Im loading images from a web service and saved to documents directory, then call the method to create the gallery. Logic is same with my other apps. But I cannot figure out what is the issue here.
I'll put here both the codes one is for retrieving data and other is the creating gallery.
Data retrieving from server
-(void)loadDataFromServer{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
arrCats = [[NSMutableArray alloc]init];
arrPromos = [[NSMutableArray alloc]init];
//[spinMenu startAnimating];
// load promo images from the server
for(int i=0;i<[arrPromos count];i++)
{
NSString *urlString = [Constants getImages:[[arrPromos objectAtIndex:i] objectForKey:#"image"]];
NSLog(#"Get Images API Call : %#", urlString);
NSURL *imageurl = [NSURL URLWithString:urlString];
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageurl];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
if(imageData != nil){
// save the images temporally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:[[arrPromos objectAtIndex:i] objectForKey:#"image"]]; //Add the file name
[imageData writeToFile:filePath atomically:YES];
}
});
});
}
// Load promotions from server
dispatch_async(queue, ^{
NSLog(#"Promotions Loading Started");
NSString *urlString = [Constants getAllPromotions:#"GetPromo.php"];
NSLog(#"Get Promotions API Call : %#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Specify that it will be a GET request
request.HTTPMethod = #"GET";
[request setHTTPShouldHandleCookies:NO];
NSURLResponse *responseURL;
NSError *error;
NSData *dataPromotions = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseURL error:&error];
if (responseURL == nil)
{
// Check for problems
if (error != nil)
{
NSLog(#"Get Promtions Connection failed! Error - %#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Error!" message:#"Promotions data failed to load!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
NSString *responseString = nil;
responseString = [[NSString alloc] initWithData:dataPromotions encoding:NSUTF8StringEncoding];
if ([responseString rangeOfString:#"error"].location == NSNotFound)
{
NSDictionary *response = [[NSDictionary alloc] init];
response = (NSDictionary *)[responseString JSONValue];
NSLog(#"Response : Promotions %#", response);
if(response != Nil){
if([response count]>0){
arrPromos = [NSMutableArray arrayWithArray:[response objectForKey:#"Promos"]];
NSLog(#"ArrPromos # loading %#", arrPromos);
// create promos galley
[self createPromosGallery];
}
}
}
}
});
Note: [self createPromosGallery]; is calling after download all the images and data.
Create Gallery
-(void) createPromosGallery{
// sort arrPromos based on priority
for(int i=0; i<[arrPromos count];i++){
[arrPromos sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
NSString *string1;
NSString *string2;
if(![[dict1 objectForKey:#"priority"] isKindOfClass: [NSNull class]])
string1 = [dict1 objectForKey:#"priority"];
if(![[dict2 objectForKey:#"priority"] isKindOfClass: [NSNull class]])
string2 = [dict2 objectForKey:#"priority"];
return [string1 compare:string2 options:NSNumericSearch];
}];
}
NSLog(#"ArrPromos %#", arrPromos);
// scrollView size
CGFloat screenHieght = [UIScreen mainScreen].bounds.size.height;
if(screenHieght>500){
scrollView.frame = CGRectMake(0, 0, 320, 568);
}
else{
scrollView.frame = CGRectMake(0, 0, 320, 480);
}
// define scrollview height
int scrollHieght;
scrollHieght = ([arrPromos count]-1)/2;
NSLog(#"Scroll height %d",scrollHieght);
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width , scrollHieght * 160 +200);
scrollView.pagingEnabled = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
scrollView.delegate = self;
for(int i=0;i<[arrPromos count];i++)
{
float x;
float y;
if(i%2==0)
{
x=30.0;
y=(i/2)*160+25;
}
if(i%2==1) {
x=170.0;
y=(i/2)*160+25;
}
// retreive saved images
NSString *strImgName;
UIImage *buttonUpImage;
// create buttons
button = [UIButton buttonWithType:UIButtonTypeCustom];
strImgName = [[arrPromos objectAtIndex:i] objectForKey:#"image"];
NSLog(#"Button image name %#", strImgName);
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",docDirectory,strImgName];
buttonUpImage = [UIImage imageWithContentsOfFile:filePath];
[button setBackgroundImage:buttonUpImage forState:UIControlStateNormal];
button.frame = CGRectMake(x, y, 120,140);
[button setTag:i];
[button addTarget:self action:#selector(promoBtnPressed:)forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
}
}
Note: I tested on both iOS 7 and 6. In iOS 7, it takes very long time to appear images on scrollView(Currently have only 2 images). Or else, If I TAP on scroolView then the images appear.
In ios 6, nothing appear
//Make a method that has url (fileName) Param
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:textPath])
{
return YES;
}
else
{
return NO;
}
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:#""]];//Placeholder image
if ([url isKindOfClass:[NSString class]])
{
imgView.image = [UIImage imageNamed:[url absoluteString]];
imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];
if (error != nil)
{
DLog(#"There was an error: %#", [error description]);
imgView.image=nil;
}
else
{
imgView.image= [UIImage imageWithData:fileData]
}
}
else
{ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint center = imgView.center;
// center.x = imgView.bounds.size.width / 2;
spinner.center = center;
[spinner startAnimating];
[imgView addSubview:spinner];
dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner removeFromSuperview];
UIImage *image = [UIImage imageWithData:imgData];
NSError *error = nil;
[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];
if (error != nil)
}
else
{
}
imgView.image = image;
});
});
}
Thats UIImageView loading an image if it doesnot exist in document then it Save it , An Activity indicator is added to show image is loading to save,
Yes it is because you are downloading and then saving the images which takes time. I suggest you to use any library for downloading images and saving them.
Ex : SDWebImage
I use this code get album pictures, and create file in the documents, but there will be Received memory warning, then crash。
Here is the code that I used. Can anyone tell me what did I do wrong?
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
NSLog(#"error occour =%#", [myerror localizedDescription]);
};
ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop){
if (result!=NULL) {
//we can get all the things in the defaultRepresentation such as size info in UTI
}
//just fetching photos
if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
//copy image to the path:Documents/DMS/Photo
ALAssetRepresentation *rep = [result defaultRepresentation];
NSString *tt = [rep filename];
NSString *fullPath = [pathPhoto stringByAppendingFormat:#"/%#",tt];
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
UIImage *image = [[UIImage alloc]initWithCGImage:[rep fullScreenImage]];
NSData *imageData = UIImagePNGRepresentation(image);
[image release];
[[NSFileManager defaultManager] createFileAtPath:fullPath contents:imageData attributes:nil];
NSLog(#"Creat image file fullPath================%#",fullPath);
//imageData = nil;
[imageData release];
}else{
NSLog(#"---------------------the image is Exist");
}
}
};
ALAssetsLibraryGroupsEnumerationResultsBlock
libraryGroupsEnumeration = ^(ALAssetsGroup* group, BOOL* stop){
if (group == nil)
{
return;
}
if (group!=nil) {
[group enumerateAssetsUsingBlock:groupEnumerAtion];
}
NSLog(#"finish--------------------------------------------");
return;
};
ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:libraryGroupsEnumeration
failureBlock:failureblock];
[library release];
[pool release];
Since you say that you are using the code you posted inside of a loop, I suppose that what happens is that you app is being killed due to too many auto-released objects being allocated inside of the loop.
You could try using an autorelease pool:
for (...) {
#autoreleasepool {
<your code here>
}
}
so that the autorelease pool is cleaned up at each iteration (instead of growing all along the whole loop execution).
EDIT:
if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
{
ALAssetRepresentation *rep = [result defaultRepresentation];
CGImageRef iref = [rep fullScreenImage];
NSString *tt = [rep filename];
if (iref)
{
UIImage *image = [UIImage imageWithCGImage:iref];
if(!image)
{
NSLog(#"---------------------the imageData is nil");
}
else
{
NSData *imageData = UIImagePNGRepresentation(image);
NSString *fullPath = [pathPhoto stringByAppendingFormat:#"/%#.png",tt];
NSLog(#"fullPath================%#",fullPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath])
{
[[NSFileManager defaultManager] createFileAtPath:fullPath contents:imageData attributes:nil];
NSLog(#"Creat image file fullPath================%#",fullPath);
}
}
CGImageRelease(iref);
}
}
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];