iOS - save image in jpg format - ios

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

Related

Data is nil from image string.

It is my save method :
-(NSString *)saveImage:(UIImage *)image
{
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 (image);
[imageData writeToFile:savedImagePath atomically:YES];
self.teamLogo = savedImagePath;
return savedImagePath;
}
I try to load image and put into control :
NSData *myData = [NSData dataWithContentsOfFile:self.team.logo];
UIImage *selectedImage = [UIImage imageWithData:myData];
self.team.logo is from DB. I keep string in base. In debug mode i got this string :
/var/mobile/Containers/Data/Application/7CD69EC9-9C20-48EE-B611-FC2353BC31B0/Documents/Image364.png
and myData is still nil. Do you have idea why ?
Starting from IOS 8 layout of containers changed. So don't store full path to your DB. Instead just store your image name. For recalling the image use:
NSString *temp = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"Image364.png"];
NSData *myData = [NSData dataWithContentsOfFile:temp];
UIImage *selectedImage = [UIImage imageWithData:myData];
I hope it helps.

Get Image from server

I am getting responseObject like this
responseObject =
{
"img": "images/ProfileImage/defaultImg.jpg",
}
I have to store this image in app folder. Is there any way to do this.
The path is incomplete
You need to append base URL before "images/ProfileImage/defaultImg.jpg"
Then
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *urlToDownload = BaseURL + "images/ProfileImage/defaultImg.jpg";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if (urlData)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"defaultImg.png"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
});
}
});
Here is the code for downloading image and store into a local i.e "Document" directory in iOS app folder
In below code urlString is the url of image.
dispatch_queue_t downloadThumbNail = dispatch_queue_create("com.download.thumbnail", NULL);
dispatch_async(downloadThumbNail, ^
{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage *imageThumb = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(),
^{
NSString *str = #“filename.png”;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:str];
NSData *pngData = UIImagePNGRepresentation(imageThumb);
[pngData writeToFile:filePath atomically:YES];
});
});
Enjoy codeing.

Download images asynchronously

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

how can i get multiple images from server using url in iOS

Hi I am getting single image from server using url in iOS.
my code is like this
- (IBAction)overlaysClicked:(id)sender
{
NSLog(#"overlays Clicked");
request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon/ov1.png"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"image.jpg"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon/ov1.png"]];
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
self.overlayImgView.image=img;
}
To get multiple images from server my code like this
NSURL *myUrl = [NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon.zip"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
myData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self startImmediately:YES];
//my Array is like this in viewDidload
self.overlaysImgsArray = [[NSMutableArray alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon.zip"]];
NSLog(#"urls is %#",overlaysImgsArray);
for (int i=0; i<[overlaysImgsArray count]; i++)
//download array have url links
{
NSURL *URL = [NSURL URLWithString:[overlaysImgsArray objectAtIndex:i]];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:URL];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if([data length] > 0 && [[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"])
{
//make your image here from data.
UIImage *imag = [[UIImage alloc] initWithData:[NSData dataWithData:data]];
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [array objectAtIndex:0];
NSString *imgstr=[NSString stringWithFormat:#"%d",i];
NSString *pngfilepath = [NSString stringWithFormat:#"%#sample%#.png",docDir,imgstr];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(imag)];
[data1 writeToFile:pngfilepath atomically:YES];
}
else if ([data length] == 0 && [[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"])
{
NSLog(#"No Data!");
}
else if (![[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"]){
NSLog(#"Error = %#", error);
}
}];
}
}
But this is not working for me please anybody suggest me how to get multiple images from server using one url which contains all the images. Please anybody
thank you in advance
In your case you can try like this
first you need to save all the 10 image in directory and the fetch one by one as your requirement .this code save all image from your url
try this
- (IBAction)overlaysClicked:(id)sender {
//Note all your image saved with ov1.png,ov2.png......& so .
for (int i=1; i<=10; i++) {
NSString *st2=#"ov";
NSString *st1=#"http://sukhada.co.in/img/overlays/neon/ov";
NSString *imageN=[st2 stringByAppendingString:[NSString stringWithFormat:#"%d",i]];
NSString *imgNameforkey=[imageN stringByAppendingString:#".png"];
NSString *url=[st1 stringByAppendingString:[NSString stringWithFormat:#"%d",i]];
NSString *imgname=[url stringByAppendingString:#".png"];
NSLog(#" all=%#",imgname);
NSLog(#"overlays Clicked");
request = [NSURLRequest requestWithURL:[NSURL URLWithString:imgname]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:imgname];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgname]];
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
NSLog(#"imgs %#",img);
// self.overlayImgView.image=img;
}
}
here you can see all image saved
fetch the image
using loop or with name
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
imagePath= [imagePath stringByAppendingPathComponent:#"ov1.png"];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *img = = [UIImage imageWithData:data];
download a zip file from url and save it .use this code inside the button action. no need for loop now. try this
- (IBAction)overlaysClicked:(id)sender {
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
NSLog(#"Beginning download");
NSString *stringURL = #"http://sukhada.co.in/img/overlays/neonra.zip";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSLog(#"Got the data!");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
//Save the data
NSLog(#"Saving");
NSString *dataPath = [path stringByAppendingPathComponent:#"img.zip"];
dataPath = [dataPath stringByStandardizingPath];
[urlData writeToFile:dataPath atomically:YES];
});
}
and check you will get img.zip file

Saving screenshot to sandbox

Is there any way to save a screenshot to the application's sandbox or some where that can be easily found to add to an email attachment? currently im saving it in the camera roll but can't seem to be able to get it to attach to my email
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *png = #".png";
NSString *filename = [drawquestion stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *link = [NSString stringWithFormat: #"%#%#%#", documentDirectory,filename,png];
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:link];
NSLog(link);
UIImageWriteToSavedPhotosAlbum(viewImage, drawquestion, nil, nil);
Here are 2 bare bones examples of how to attach an image to an email.
// with UIImage * image;
MFMailComposeViewController * mfcvc = [[[MFMailComposeViewController alloc] init] autorelease];
NSData * imageData = UIImagePNGRepresentation(image);
[mfcvc addAttachmentData:imageData mimeType:#"image/png" fileName:#"demo"];
[self.viewController presentModalViewController:mfcvc animated:YES];
// with UIImage * image; and float compression_quality; between 0.0 and 1.0
MFMailComposeViewController * mfcvc = [[[MFMailComposeViewController alloc] init] autorelease];
NSData * imageData = UIImageJPEGRepresentation(image, compression_quality);
[mfcvc addAttachmentData:imageData mimeType:#"image/jpeg" fileName:#"demo"];
[self.viewController presentModalViewController:mfcvc animated:YES];
To save the image in the documents directory in the app's sandbox
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *png = #".png";
NSString *filename = [drawquestion stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *imagePath = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#%#",filename, png]];
[imageData writeToFile:imagePath atomically:YES];
PS
I cleaned up the construction of the path, it seems your code has a path like
/var/mobile/Applications/APP_ID//var/mobile/Applications/APP_ID/Documents/filename.png
You should check out writeToFile:atomically: you get your image data, and write it to a file, this will save to the application's sandbox.
Check out this for some example code: http://blog.objectgraph.com/index.php/2010/04/05/download-an-image-and-save-it-as-png-or-jpeg-in-iphone-sdk/
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"%#",docDir);
NSLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
// You should swap data for your image data
NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data writeToFile:pngFilePath atomically:YES];
You can then use the addAttachmentData:mimeType:fileName: method on MFMailComposeViewController class to attach an attachment (actually you don't even need to save the image to disk):
MFMailComposeViewController * mailVC = [[MFMailComposeViewController alloc] init];
NSData *data; // this is the data from earlier
[mailVC addAttachmentData:data mimeType:#"image/png" fileName:#"myfilename"];
[self presentModalViewController:mailVC animated:YES];
Be sure to have a correct MIME type set here. The file name you can set to what you want, it is the name of the file in the attachment as seen by the recipient.

Resources