Code
StreamPtr pStm;
pStm.CreateInstance("ADODB.Stream");
variant_t varOptional(DISP_E_PARAMNOTFOUND,VT_ERROR);
pStm->PutType(adTypeBinary);//类型为二进制
//得到字段内容的大小
long lDataSize = m_pRecordset->GetFields()->GetItem("photo")->ActualSize;
//m_pRecordset为一个打开的纪录集对象,含有photo这个blob字段
pStm->Open( varOptional,
adModeUnknown, adOpenStreamUnspecified, _bstr_t(), _bstr_t());
//打开pStm
pStm->Write(_variant_t(m_pRecordset->GetFields()->GetItem("photo")->Value));
//把photo字段的内容写入pStm
pStm->SaveToFile("c:\\publogo.jpg", adSaveCreateOverWrite);
pStm->Close();
//直接保存为文件,如果是别的格式只要保存的时候改变后缀就可以了
下面是如果不保存成文件可以直接通过Com对象来绘制该图片,IPicture 可以显示多种格式图片.
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, pStm->GetSize());
LPVOID pvData = NULL;
IStream *ps;
if (hGlobal != NULL)
{
if ((pvData = GlobalLock(hGlobal)) != NULL)
{
char * m_pBMPBuffer = new char[pStm->GetSize()+1];//分配必要的存储空间
char *pBuf = NULL;
SafeArrayAccessData(varBLOB.parray,(void **)&pBuf);
memcpy(pvData,pBuf,pStm->GetSize()); //复制数据到缓冲 区 m_pBMPBuffer
SafeArrayUnaccessData (varBLOB.parray);
GlobalUnlock(hGlobal);
CreateStreamOnHGlobal(hGlobal, TRUE, &ps);
}
}
IPicture *pPic;
if(SUCCEEDED(OleLoadPicture(ps,pStm->GetSize() ,TRUE,IID_IPicture,(LPVOID*)&pPic)))
{
OLE_XSIZE_HIMETRIC hmWidth;
OLE_YSIZE_HIMETRIC hmHeight;
pPic->get_Width(&hmWidth);
pPic->get_Height(&hmHeight);
double fX,fY;
CDC *pDC = GetClientDC();//这里根据具体请况来取
fX=(double)pDC->GetDeviceCaps(HORZRES)*(double)hmWidth/((double)pDC->GetDeviceCaps(HORZSIZE)*100.0);
fY =(double)pDC->GetDeviceCaps(VERTRES)*(double)hmHeight/((double)pDC->GetDeviceCaps(VERTSIZE)*100.0);
if(FAILED(pPic->Render(*pDC,0,0,(DWORD)fX,(DWORD)fY,0,hmHeight,hmWidth,-hmHeight,NULL)))
AfxMessageBox("图像绘制失败!");
pPic->Release();
}
这样就完成了对图片文件从数据库读出和显示的过程。
对于从文件写入数据库就相对的容易多了,
_StreamPtr pStm;
pStm.CreateInstance("ADODB.Stream");
variant_t varOptional(DISP_E_PARAMNOTFOUND,VT_ERROR);
long lDataSize = m_pRecordset->GetFields()->GetItem("photo")->ActualSize;
pStm->PutType(adTypeBinary;
pStm->Open( varOptional,
adModeUnknown, adOpenStreamUnspecified, _bstr_t(), _bstr_t());
pStm->LoadFromFile("c:\\book.gif");//读入文件
variant_t varBLOB=pStm->Read(adReadAll);
m_pRecordset->GetFields()->GetItem("photo")->Value= varBLOB;//保存到数据集对象。