开发者

Get image from SQL in iOS

I have a stored ima开发者_StackOverflow中文版ge (as data) in SQL, how do I recreate a image object in iOS using this SQL data?

Thanks


it would be easier if you use SQLite and fmdb. The code for storing and retrieving images using fmdb follows.

// let's read in an image from safari's app bundle.
NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"];
if (safariCompass) {
    [db executeUpdate:@"insert into blobTable (a, b) values (?,?)", @"safari's compass", safariCompass];

    rs = [db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"];
    if ([rs next]) {
        safariCompass = [rs dataForColumn:@"b"];
        [safariCompass writeToFile:@"/tmp/compass.icns" atomically:NO];

        // let's look at our fancy image that we just wrote out..
        system("/usr/bin/open /tmp/compass.icns");

        // ye shall read the header for this function, or suffer the consequences.
        safariCompass = [rs dataNoCopyForColumn:@"b"];
        [safariCompass writeToFile:@"/tmp/compass_data_no_copy.icns" atomically:NO];
        system("/usr/bin/open /tmp/compass_data_no_copy.icns");
    }
    else {
        NSLog(@"Could not select image.");
    }

    [rs close];

}
else {
    NSLog(@"Can't find compass image..");
}

The code is taken directly from the fmdb git repo.


You haven't said how exactly you stored the image into your SQL database; I guess it was something along the lines of using UIImageJPEGRepresentation to convert the image to an NSData object and then serialize that NSData object somehow.

To create an image from a NSData object, use [UIImage imageWithData:...]. This will parse image data in jpeg, png, or a few other formats.


Create a NSData object with your raw image data from your SQL database:

NSData * rawData = [ NSData dataWithBytes: xxx length: xxx ];

The create an image from your data object:

UIImage * img = [ [ UIImage alloc ] initWithData: rawData ];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜