将远程图像保存到文档/图像文件夹

时间:2011-04-29 12:04:32

标签: iphone cocoa

我已经检查过这里发布的其他问题的每个答案,但似乎没有答案可行。

我试图将网站上的图像(例如http://dl.kr.org/logos/dl-small.gif)保存到iphone上的Documents / Images文件夹中。

有人可以将我需要的代码粘贴给我,我已经尝试了长而小的答案,但没有一个能够正常工作

2 个答案:

答案 0 :(得分:1)

试试此代码..

// Get an image from the URL below
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.objectgraph.com/images/og_logo.png"]]];

NSLog(@"%f,%f",image.size.width,image.size.height);

// Let's save the file into Document folder.
// You can also change this to your desktop for testing. (e.g. /Users/kiichi/Desktop/)
// NSString *deskTopDir = @"/Users/kiichi/Desktop";

NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

// If you go to the folder below, you will find those pictures
NSLog(@"%@",docDir);

NSLog(@"saving png");
NSString *pngFilePath = [NSString stringWithFormat:@"%@/test.png",docDir];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];

NSLog(@"saving jpeg");
NSString *jpegFilePath = [NSString stringWithFormat:@"%@/test.jpeg",docDir];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];

NSLog(@"saving image done");

[image release];

答案 1 :(得分:1)

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://dl.kr.org/logos/dl-small.gif"]];

NSString *imagePath = [NSString stringWithFormat:@"%@/dl-small.gif", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];

[data writeToFile:imagePath atomically:NO];