簡體   English   中英

在iOS中下載和保存圖像

[英]Downloading and saving images in iOS

我正在創建一個iPhone應用程序,因此我想從Web服務下載多個圖像文件。 我想將圖像保存在應用程序本身的本地文件夾中,並將路徑保存到SQLite數據庫中的每個文件。 我該如何實施? 請幫忙。

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

>>更新附加:

您需要將圖像名稱(可以盡早使用的唯一名稱..right .. !!)保存在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.

希望這個能對您有所幫助...

在實現@Nit的代碼后,您可以參考以獲取數據庫中的插入記錄。

這顯示了如何在數據庫中插入記錄。 為了獲取路徑,請閱讀@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中顯示圖像

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM