I am currently working IOS application which can be used to upload multiple image to ftp server. I am using GoldRaccoon class file. I have selected 5 images, but it only uploads the last image.
- (void)zcImagePickerController:(ZCImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(NSArray *)info {
[self dismissPickerView];
NSString *fullPath;
for (NSDictionary *imageDic in info) {
UIImageView *imageView = [[UIImageView alloc] initWithImage:[imageDic objectForKey:UIImagePickerControllerOriginalImage]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[arrImageView addObject:imageView];
UIImage *image1 = [imageDic objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData * imageData1 = UIImageJPEGRepresentation(image1,100); //convert image into .png format.
NSFileManager * fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray * paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString * documentsDirectory = [paths1 objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg",image1]]; //add our image to the path
// NSString *str=[NSString stringWithFormat:#"%#.jpg",image1];
[fileManager createFileAtPath:fullPath contents:imageData1 attributes:nil]; //finally save the image
[arrvalue addObject:fullPath];
NSURL *imageURL = [imageDic valueForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibraryAssetForURLResultBlock resultblock =^(ALAsset *myasset)
{
ALAssetRepresentation *representation = [myasset defaultRepresentation];
NSString *fileName = [representation filename];
// Send WebService
// [arrName addObject:fileName];
[self sendImage:fileName :fullPath];
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init] ;
[assetslibrary assetForURL:imageURL resultBlock:resultblock failureBlock:nil];
}
}
Related
when i capture the image i need to save images one by one in table view like below image .is need use nsuser defaults or use core data?
and after picking the image how to add to Array
You can save image in NSUserDefaults as follows,
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
if(!self.phto_arr_)
{
self.phto_arr_ = [[NSMutableArray alloc] init];
}
[self.phto_arr_ addObject: chosenImage];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self.phto_arr_];
[[NSUserDefaults standardUserDefaults] setObject: encodedObject forKey:#"images"];
[[NSUserDefaults standardUserDefaults] synchronize];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
Yes, you can save the images in the document directory and keep the image file names in an array after that retrieve that images from doc. dir. just like this
// For error information
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/YOUR_IMG_FOLDER"];
if (![fileMgr fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
//Get the current date and time and set as image name
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd_HH-mm-ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *gmtTime = [dateFormatter stringFromDate:now];
NSLog(#"The Current Time is :%#", gmtTime);
NSData *imageData = UIImageJPEGRepresentation(_postImage, 0.5); // _postImage is your image file and you can use JPEG representation or PNG as your wish
int imgSize = imageData.length;
////NSLog(#"SIZE OF IMAGE: %.2f Kb", (float)imgSize/1024);
NSString *imgfileName = [NSString stringWithFormat:#"%#%#", gmtTime, #".jpg"];
// File we want to create in the documents directory
NSString *imgfilePath= [dataPath stringByAppendingPathComponent:imgfileName];
// Write the file
[imageData writeToFile:imgfilePath atomically:YES];
**// Keep your Image file name into an mutable array here OR you can saved the array in a UserDefaults**
Then retrieve from doc. dir. from iterate the array.
//Get image file from sand box using file name and file path
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"YOUR_IMG_FOLDER"];
stringPath = [stringPath stringByAppendingPathComponent:imgFile]; // imgFile to get from your array, where you saved those image file names
UIImage *image = [UIImage imageWithContentsOfFile:stringPath];
Thank you...happy coding.
Try below this code:
suppose you want to image name also display use this code,
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
chosenImage = info[UIImagePickerControllerOriginalImage];
chosenImage = [UIImage unrotateImage:chosenImage];
addGalleryImageview.image = chosenImage;
isCameraOn = YES;
NSString* fileName = [NSString stringWithFormat:#"gallery%#",[Utils getDateString]];
imageNamelbl.text = fileName;
[picker dismissViewControllerAnimated:YES completion:NULL];}
- (UIImage*)unrotateImage:(UIImage*)image{
CGSize size = image.size;
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0,0,size.width ,size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}
I am using the following code to download images. Can someone confirm the images are being downloaded asynchronously as they would appear to be? Normally, they download rapidly but every now and then the UI freezes for a minute while data comes through so something would appear to be awry:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
NSString *picURL = [NSString stringWithFormat:#"http://~/pics/%#",picname];
NSURL *urlPicUrl = [NSURL URLWithString:picURL];
dispatch_async(kBgQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:picURL]];
if (imgData) {
UIImage *imageCache = [[UIImage alloc] init];
imageCache = [UIImage imageWithData:imgData];
if (imageCache) {
[self saveImage:imageCache asPicName:picname];
dispatch_async(dispatch_get_main_queue(), ^{
});
}
}
});
EDIT:
Here is code to save image.
- (void)saveImage: (UIImage*)image asPicName: (NSString*)picname
{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: picname] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
When I tried to copy a video from album to app using UIImagePickerController, the video is compressed.
When the video imported via Photos app on Mac, the ten-second long video is:
1920x1280 ~22MB
After the video is imported into app, then copied via iTunes Sharing, the compressed video is:
1280x720 ~6.3MB
How can I import video into app in original resolution and quality?
Code:
- (void)importVideo:(id)sender {
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
imagePickerController.allowsEditing = YES;
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if (CFStringCompare((__bridge_retained CFStringRef)mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [paths firstObject];
NSString *filename = [folder stringByAppendingPathComponent:self.uniqueFilename];
BOOL success = [videoData writeToFile:filename atomically:NO];
NSLog(#"Write to file %#", success ? #"OK" : #"Error");
}
}
Once a PHAsset is obtained via GMImagePicker, it can be saved by:
for (PHAsset *asset in assetArray) {
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset
options:options
resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
if ([avAsset isKindOfClass:[AVURLAsset class]]) {
NSURL *videoURL = [(AVURLAsset *) avAsset URL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [paths firstObject];
NSString *filename = [folder stringByAppendingPathComponent:#"foo.mp4"];
[videoData writeToFile:filename atomically:NO];
}
}];
}
My question is what format the image is saved, if is dat or jpg. This is the code that i used:
NSString * urlImage = .....;
NSString * _folderPath = .....;
NSString * imageName = [[urlImage componentsSeparatedByString:#"/"] lastObject];
NSString * jpegPath = [NSString stringWithFormat:#"%#%#",_folderPath,imageName];
if (![[NSFileManager defaultManager] fileExistsAtPath:jpegPath])
{
NSURL *url = [NSURL URLWithString:urlImage];
//Download image
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];
//Save image
NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data writeToFile:jpegPath atomically:YES];
}
Following is piece of code for save .jpg image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path = [docs stringByAppendingFormat:#"/image1.jpg"];
NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(imageView.image, 80)];
NSError *writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];
You should use
stringByAppendingPathComponent method to create or get exact valid path
Use this way:
NSString * jpegPath = [_folderPath stringByAppendingPathComponent:imageName];// [NSString stringWithFormat:#"%#%#",_folderPath,imageName];
I want to retrieve a folder containing 10 images from server, then store that folder in my document directory. I did some code, but when I run it, I am getting the image urls, not the images themselves. Can anyone help me out?
My code:
-(void)viewWillAppear:(BOOL)animated
{
NSMutableData *receivingData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:#"http://Someurl.filesCount.php"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivingData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
printf("\n the path is :%s",[path UTF8String]);
NSString *zipPath = [path stringByAppendingPathComponent:#"filesCount.php"];
[receivingData writeToFile:zipPath options:0 error:&error];
NSString *documentsDirectoryPath = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"filesCount"];
NSLog(#"the path %#",documentsDirectoryPath);
}
I made this function in my previous project. You need to pass your imageView and serverUrl, then its automatically show image in your imageView and save image to temp directory, when you want again to fetch same image, then next time it take image from disk.
+(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{
NSFileManager *fileManager =[NSFileManager defaultManager];
NSString* theFileName = [NSString stringWithFormat:#"%#.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
actView.frame = frameToCenter;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *dataFromFile = nil;
NSData *dataFromUrl = nil;
dataFromFile = [fileManager contentsAtPath:fileName];
if(dataFromFile==nil){
dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
}
dispatch_sync(dispatch_get_main_queue(), ^{
if(dataFromFile!=nil){
imgView.image = [UIImage imageWithData:dataFromFile];
}else if(dataFromUrl!=nil){
imgView.image = [UIImage imageWithData:dataFromUrl];
// NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
if(filecreationSuccess == NO){
NSLog(#"Failed to create the html file");
}
}else{
imgView.image = [UIImage imageNamed:#"NO_Image.png"];
imgView.tag = 105;
}
[actView removeFromSuperview];
[actView release];
});
});
}
Try using this code.
NSURL* url = [NSURL URLWithString:#"http://imageAddress.com"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
// do whatever you want with directory or store images.
NSImage* image = [[NSImage alloc] initWithData:data];
}
}];
Use this code to download the image using URL and store in document directory. Iterate the logic for set of images to download and store.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imageURL = #"http://sampleUrl";
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Image1.png"]];
if(image != NULL)
{
//Store the image in Document
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile: imagePath atomically:YES];
}
If you'll showing the images loaded from server on UI, then
try SDWebImageView, can be used with UIButton or UIImageView, very easy and efficient.
example,
[yourImageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Read how to use it?
Okay, now for multiple images, you may need to run a loop, if you've a common base url for all your pictures (on server) something like http://yoururl/server/pictures/1.png will be replace by 2.png 3.png ... n.png, or you get different urls for pictures need to pass that url, you can load it into imageview objects, and later save them into document directory (remember, SDWebImageView by default doing this work for you). You can turn this off too.
P.S. It will load images once and stored into local (in cache) it self, next time when you pass the same image url, it won't load from server and directly load the image from local.