1

私は iPhone アプリを作成しており、Web サービスから複数の画像ファイルをダウンロードしたいと考えています。そして、アプリ自体のローカル フォルダーに画像を保存し、各ファイルへのパスを SQLite データベースに保存したいと考えています。どうすればこれを実装できますか? 助けてください。

4

2 に答える 2

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

>>追加の更新:

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.

うまくいけば、これはあなたを助けるでしょう...

于 2012-05-07T12:07:40.010 に答える
2

@Nitのコードを実装した後、データベースにレコードを挿入するためにこれを参照できます。

これは、DBにレコードを挿入する方法を示しています。パスを取得するには、@Nitの回答にある私のコメントを読んでください。

アップデート:

ダウンロードした各ファイルのパスを取得するには、各ファイルの一意の名前を保持する必要があります。これで、すべてのファイルに固有のパスであるファイルを書き込んでいるパスが得られます。これで、ファイルをダウンロードするたびに挿入クエリを実行するか、ファイルパスを配列に保存して、要件に応じて後でクエリを実行する必要があります。すべてのファイルに異なるファイル名を付けることを忘れないでください。そうしないと、1つのファイルだけが存在し、パスは同じになります。

一意のファイル名を取得するには、タイムスタンプを使用できます。

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;

これにより、画像ビューに画像が表示されます

お役に立てれば

于 2012-05-07T12:16:41.097 に答える