Young Young - 5 months ago 34
C++ Question

Load image from binary in MFC

Usually I do the image-loading using LoadImage with path or LoadBitmap with resource ID. But now the target image resource is stored in database(SQLite). So how can I use the binary data directly(avoiding store temporary file) retrieved from the db in MFC?


Here's the solution I found out ,and it works fine in my project.

1.function for retrieve binary data from sqlite database.

int CSqlite::retrieveBinaryData(int id , byte *pdata)
    ASSERT(pdata != NULL);
    int rc,size;
    sqlite3_stmt * stmt;

    sqlite3_prepare(dbh,"select id,content,size from images where id = ?",-1,&stmt,0);

    rc = sqlite3_step(stmt);

    if(rc == SQLITE_ROW)
        num = sqlite3_column_int(stmt,0);

        size = sqlite3_column_int(stmt,2);
        byte *tmpdata  = (byte * )sqlite3_column_blob(stmt,1);
        return size;
    return 0;

2.receive the data from function above and convert it to CBitmap so we can use it.

    byte *tdata = new BYTE[BMP_MAX_SIZE];
    CSqlite *sq = new CSqlite("mysqlite.db");
    int size = sq->retrieveBinaryDatas(myid,tdata);

        /* using the resource mentioned by alfonso in the comment */

    bmfh = (BITMAPFILEHEADER*)tdata;

    bmih = (BITMAPINFOHEADER*)(tdata + sizeof(BITMAPFILEHEADER));
    BITMAPINFO* bmi;
    bmi = (BITMAPINFO*)bmih;

    void* bits;
    bits = (void*)(tdata + bmfh->bfOffBits);

    HDC hdc = ::GetDC(NULL);

    HBITMAP hbmp = CreateDIBitmap(hdc, bmih, CBM_INIT, bits, bmi, DIB_RGB_COLORS) ;

    ::ReleaseDC(NULL, hdc);
    delete tdata;

    BITMAP bitmap; 
    CBitmap   *bmpBackground =  CBitmap::FromHandle(hbmp);