给一个用vb调用的例子:
注:写图片文件到数据库
Col为栏位名,ImgFile为要写到数据库的图片文件名,BockSize为每次写多少字节,缺省为每次写8K字节到数据库
Public Sub WriteDB(Col As ADODB.Field, ImgFile As String, Optional BlockSize As Long=8192)
Dim byteData() As Byte, FileLength As Long, NumBlocks As Integer
Dim LeftOver As Long, SourceFileNum As Integer, i As Integer
SourceFileNum = FreeFile
Open ImgFile For Binary As SourceFileNum
FileLength = LOF(SourceFileNum)
If FileLength > 50 Then
NumBlocks = FileLength \ BlockSize
LeftOver = FileLength Mod BlockSize
ReDim byteData(LeftOver)
Get SourceFileNum, , byteData()
Col.AppendChunk byteData()
ReDim byteData(BlockSize)
For i = 1 To NumBlocks
Get SourceFileNum, , byteData()
Col.AppendChunk byteData()
Next
End If
Close SourceFileNum
End Sub
ImgFile为从数据库读出数据写到磁盘的文件名,BlockSize为每次向文件写多少个字节,缺省为8K字节,当ReadDB=True,得到图片文件後,可以用LoadPicter(图片文件名)显示图片到PictureBox或Image框中.
Public Function ReadDB(Col As ADODB.Field, ImgFile As String,Optional BlockSize As Long=8192) As Boolean
Dim byteData() As Byte, NumBlocks As Integer
Dim LeftOver As Long, DestFileNum As Integer, i As Integer
Dim ColSize As Long
On Error GoTo ErrRead
ReadDB = False
'If Dir(ImgFile) <> "" Then Kill ImgFile
DestFileNum = FreeFile
Open ImgFile For Binary As #DestFileNum
ReDim byteData(LeftOver)
byteData() = Col.GetChunk(LeftOver)
Put DestFileNum, , byteData()
ReDim byteData(BlockSize)
For i = 1 To NumBlocks
byteData() = Col.GetChunk(BlockSize)
Put #DestFileNum, , byteData()
Next
If LOF(DestFileNum) > 200 Then ReadDB = True
Close #DestFileNum
Exit Function
ErrRead:
MsgBox "READ PICTURE ERR:" & Err.Number
ReadDB = False
Exit Function
End Function//如果ReadDB=False则写文件失败。