ios 向sqlite數據庫插入和讀取圖片數據


向sqlite數據庫插入和讀取圖片數據 (for ios)

假定數據庫中存在表 test_table(name,image), 下面代碼將圖片文件test.png的二進制數據寫到sqlite數據庫:
char *name = "test";
NSString * nameString = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
NSString * filePath = [[NSBundle mainBundle] pathForResource:nameString ofType:@"png"];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
    NSData * imgData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:filePath]);
    const  char * sequel = "insert into test_table(name,image) values(?,?)";
 
    sqlite3_stmt * update;
    if (sqlite3_prepare_v2(database, sequel, -1, &update, NULL) == SQLITE_OK)
    {
        sqlite3_bind_text(update, 1, name, -1, NULL);
        sqlite3_bind_blob(update, 2, [imgData bytes], [imgData length], NULL);
        if( sqlite3_step(update) == SQLITE_DONE)
        {
           NSLog(@"已經寫入數據");
        }
        sqlite3_finalize(update);
    }  
}
else
{
    NSLog(@"文件不存在");
}

下面代碼從數據庫中讀取圖片二進制數據,然后顯示圖片:
const char * sequel = "select image from test_table where name=?";
sqlite3_stmt * getimg;
if (sqlite3_prepare_v2(database, sequel, -1, &getimg, NULL) == SQLITE_OK)
{
    char *name = "test";
    sqlite3_bind_text(update, 1, name, -1, NULL);
    if(sqlite3_step(getimg)  == SQLITE_ROW)
    {
        int bytes = sqlite3_column_bytes(getimg, 0);
        Byte * value = (Byte*)sqlite3_column_blob(getimg, 1);
        if (bytes !=0 && value != NULL)
        {
            NSData * data = [NSData dataWithBytes:value length:bytes];
            UIImage * img = [UIImage imageWithData:data];
            UIImageView * aview =[[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, IMAGE_WIDTH, IMAGE_HEIGHT)];
            aview.image = img;
            [self.view addSubview:aview];
            [aview release];
         }
     }
     sqlite3_finalize(getimg);
}

 

轉:http://blog.csdn.net/moliyll/article/details/7953656

參考:http://wiki.eoe.cn/page/iOS_blog_page_96451.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM