在iOS中下载和保存图像

时间:2012-05-07 12:01:58

标签: iphone image save download

我正在创建一个iPhone应用程序,我想从Web服务下载多个图像文件。我想将图像保存在应用程序本身的本地文件夹中,并保存SQLite数据库中每个文件的路径。我该如何实现呢?请帮忙。

2 个答案:

答案 0 :(得分:10)

**// Get an image from the URL below**
    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"yorimageurl"]]];

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

    **// Let's save the file into Document folder.**

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

    NSString *pngPath = [NSString stringWithFormat:@"%@/test.png",Dir];// this path if you want save reference path in sqlite 
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [data1 writeToFile:pngFilePath atomically:YES];

    NSLog(@"saving jpeg");
    NSString *jpegPath = [NSString stringWithFormat:@"%@/test.jpeg",Dir];// this path if you want save reference path in sqlite 
    NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
    [data2 writeToFile:jpegFilePath atomically:YES];

    NSLog(@"saving image done");

    [image release];

<强>&GT;&GT;更新附加:

您需要在sqlite数据库中保存图像名称(您可以提前做的唯一名称......正确!!),然后您可以使用该名称创建路径或检索图像,如下所示。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"test.png"];// here you jus need to pass image name that you entered when you stored it.

希望,这会对你有帮助......

答案 1 :(得分:2)

在实施@Nit的代码之后......您可以在This中引用数据库中的插入记录。

这显示了如何在DB中插入记录。并且在@ Nit的答案中读取我的评论。

<强>更新

要获取每个下载文件的路径,您必须为每个文件保留唯一名称。现在,您将拥有编写文件的路径,该文件是每个文件的唯一路径。现在,您只需在每次下载文件时执行插入查询,或者需要在文件中保存文件路径并根据您的要求执行查询。不要忘记为每个文件指定不同的文件名,否则只有单个文件,并且您的路径将是相同的。

要获取唯一文件名,您可以使用时间戳:

NSString *fileName = [NSString stringWithFormat:@"%lf.png", [[NSDate date] timeIntervalSince1970];

<强> UPDATE2:

您现在拥有路径:/Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/84A837AA-7881-4D99-B6E2-623DC9A2E5D3/Documents/test.png

在图像视图中获取图像:

UIImage *img = [UIImage imageWithContentsOfFile:yourPath];
//[UIImage imageWithData:[NSData dataWithContentsOfFile:yourPath]];
UIImageView *imgView = // Alloc + Init + Setting frame etc
imgView.image = img;

这将在您的imageview中显示图片

希望这有帮助