How do I load and save an image from an SQL Server database using GDI+ and C++?

风流意气都作罢 提交于 2019-12-04 01:34:56

问题


I need specifically to load a JPG image that was saved as a blob. GDI+ makes it very easy to retrieve images from files but not from databases...


回答1:


Take a look at Image::Image(IStream *, BOOL). This takes a pointer to a COM object implementing the IStream interface. You can get one of these by allocating some global memory with GlobalAlloc and then calling CreateStreamOnHGlobal on the returned handle. It'll look something like this:

shared_ptr<Image> CreateImage(BYTE *blob, size_t blobSize)
{
    HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE,blobSize);
    BYTE *pImage = (BYTE*)::GlobalLock(hMem);

    for (size_t iBlob = 0; iBlob < blobSize; ++iBlob)
        pImage[iBlob] = blob[iBlob];

    ::GlobalUnlock(hMem);

    CComPtr<IStream> spStream;
    HRESULT hr = ::CreateStreamOnHGlobal(hMem,TRUE,&spStream);

    shared_ptr<Image> image = new Image(spStream);  
    return image;
}

But with error checking and such (omitted here to make things clearer)




回答2:


First fetch your blog into a byte array then use something like this:

public static Image CreateImage(byte[] pict)
{
   System.Drawing.Image img = null;
   using (System.IO.MemoryStream stream = new System.IO.MemoryStream(pict)) {
    img = System.Drawing.Image.FromStream(stream);
   }
   return img;
}


来源:https://stackoverflow.com/questions/192124/how-do-i-load-and-save-an-image-from-an-sql-server-database-using-gdi-and-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!