源代码:下载
简述关键代码如下:
1、保存图片数据到数据库
//BMP图片保存到数据库
try
{
_RecordsetPtr pRecordset;
pRecordset.CreateInstance(__uuidof(Recordset));
pRecordset->Open("SELECT * FROM bmp",_variant_t((IDispatch*)pConnection),adOpenStatic,adLockOptimistic,adCmdText);
pRecordset->AddNew();
pRecordset->Fields->Item["bmpid"]->Value = (_variant_t)m_BMPId; //bmpid
VARIANT pvList;
SetPictureToVariant(pvList,(unsigned char *)m_pBMPBuffer);
pRecordset->Fields->Item["bmpimage"]->AppendChunk(pvList); //BMP图像文件
VariantClear(&pvList);
pRecordset->Update();
pRecordset->Close();
AfxMessageBox("BMP图像保存成功!");
}
catch(...)
{
AfxMessageBox("数据库读取失败");
return;
}
其中SetPictureToVariant如下:
void CBMPinDBDlg::SetPictureToVariant(VARIANT &pvList, unsigned char *sPicture)
{
SAFEARRAYBOUND saBound[1];
saBound[0].cElements = m_nFileLen;
saBound[0].lLbound = 0;
SAFEARRAY *pSA = SafeArrayCreate(VT_UI1, 1, saBound);
for (long l = 0; l < (long)m_nFileLen; l ++)
{
SafeArrayPutElement( pSA, &l, (void*)&sPicture[l]);
}
VariantClear(&pvList);
pvList.vt = VT_UI1 | VT_ARRAY;
pvList.parray = pSA;
}
2、从数据库读取图像文件并且显示在界面
//从数据库里取BMP图像文件
try
{
_RecordsetPtr pRecordset;
char sSql[129];
sprintf(sSql,"SELECT *FROM bmp WHERE bmpid='%s'",m_BMPId);
pRecordset.CreateInstance(__uuidof(Recordset));
pRecordset->Open(sSql,_variant_t((IDispatch*)pConnection),adOpenStatic,adLockOptimistic,adCmdText);
if (pRecordset->adoEOF)
{
CString str;
str.Format("没有BMPid为: %s 的BMP图像!",m_BMPId );
AfxMessageBox(str);
DestroyPhoto();
Invalidate();
m_BMPId = "";
UpdateData(false);
m_EidtBMPId.SetFocus();
return;
}
_variant_t pvList ;
long lDataSize = pRecordset->GetFields()->GetItem("bmpimage")->ActualSize;
m_nFileLen = (DWORD)lDataSize;
if(lDataSize > 0)
{
_variant_t varBLOB;
varBLOB = pRecordset->GetFields()->GetItem("bmpimage")->GetChunk(lDataSize);
//把二进制格式的图片转为图片格式
if(varBLOB.vt == (VT_ARRAY | VT_UI1))
{
if(m_pBMPBuffer = new char[lDataSize+1])
{
char *pBuf = NULL;
SafeArrayAccessData(varBLOB.parray,(void **)&pBuf);
memcpy(m_pBMPBuffer,pBuf,lDataSize);
SafeArrayUnaccessData (varBLOB.parray);
m_nFileLen = lDataSize;
m_hBitmap = BufferToHBITMAP();
Invalidate();//在界面显示
}
}
}
}
catch(...)
{
AfxMessageBox("数据库读取失败");
return;
}
上次写了两篇关于在VC界面显示图片(BMP、JPG)的文章,但是并没有涉及到数据库,所以这次补写了这两篇有关数据库的文章,这两篇文章用的是access的数据库,其它的数据库操作道理是一样的。
具体的程序请参考附带的例子,例子里面有详细的注释。