用VB6读写数据库中的图片 1,以人名和相关图片为例说明,数据库为Access,有如下字段:Name char,picture OLE object,FileLength 
Number。当为ms sql时,将picture改为lob即可。 
2,示例包含control:commom dialog,picture,listbox。 
源码如下: 
Option Explicit Private Declare Function GetTempFileName Lib "kernel32" Alias "GetTempFileNameA" (ByVal lpszPath As 
String, ByVal lpPrefixString As String, ByVal wUnique As Long, ByVal lpTempFileName As String) As Long 
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, 
ByVal lpBuffer As String) As Long 
Private Const MAX_PATH = 260 Private m_DBConn As ADODB.Connection Private Const BLOCK_SIZE = 10000 
注释: Return a temporary file name. 
Private Function TemporaryFileName() As String 
Dim temp_path As String 
Dim temp_file As String 
Dim length As Long 注释: Get the temporary file path. 
temp_path = Space$(MAX_PATH) 
length = GetTempPath(MAX_PATH, temp_path) 
temp_path = Left$(temp_path, length) 注释: Get the file name. 
temp_file = Space$(MAX_PATH) 
GetTempFileName temp_path, "per", 0, temp_file 
TemporaryFileName = Left$(temp_file, InStr(temp_file, Chr$(0)) - 1) 
End Function 
Private Sub Form_Load() 
Dim db_file As String 
Dim rs As ADODB.Recordset 注释: Get the database file name. 
db_file = App.Path 
If Right$(db_file, 1) <> "" Then db_file = db_file & "" 
db_file = db_file & "dbpict.mdb" 注释: Open the database connection. 
Set m_DBConn = New ADODB.Connection 
m_DBConn.Open _ 
"Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
"Data Source=" & db_file & ";" & _ 
"Persist Security Info=False" 注释: Get the list of people. 
Set rs = m_DBConn.Execute("SELECT Name FROM People ORDER BY Name", , adCmdText) 
Do While Not rs.EOF 
lstPeople.AddItem rs!Name 
rs.MoveNext 
Loop rs.Close 
Set rs = Nothing 
End Sub 
Private Sub Form_Resize() 
lstPeople.Height = ScaleHeight 
End Sub 
注释: Display the clicked person. 
Private Sub lstPeople_Click() 
Dim rs As ADODB.Recordset 
Dim bytes() As Byte 
Dim file_name As String 
Dim file_num As Integer 
Dim file_length As Long 
Dim num_blocks As Long 
Dim left_over As Long 
Dim block_num As Long 
Dim hgt As Single picPerson.Visible = False 
Screen.MousePointer = vbHourglass 
DoEvents 注释: Get the record. 
Set rs = m_DBConn.Execute("SELECT * FROM People WHERE Name=注释:" & _ 
lstPeople.Text & "注释:", , adCmdText) 
If rs.EOF Then Exit Sub 注释: Get a temporary file name. 
file_name = TemporaryFileName() 注释: Open the file. 
file_num = FreeFile 
Open file_name For Binary As #file_num 注释: Copy the data into the file. 
file_length = rs!FileLength 
num_blocks = file_length / BLOCK_SIZE 
left_over = file_length Mod BLOCK_SIZE For block_num = 1 To num_blocks 
bytes() = rs!Picture.GetChunk(BLOCK_SIZE) 
Put #file_num, , bytes() 
Next block_num If left_over > 0 Then 
bytes() = rs!Picture.GetChunk(left_over) 
Put #file_num, , bytes() 
End If Close #file_num 注释: Display the picture file. 
picPerson.Picture = LoadPicture(file_name) 
picPerson.Visible = True Width = picPerson.Left + picPerson.Width + Width - ScaleWidth 
hgt = picPerson.Top + picPerson.Height + Height - ScaleHeight 
If hgt < 1440 Then hgt = 1440 
Height = hgt Kill file_name 
Screen.MousePointer = vbDefault 
End Sub Private Sub mnuRecordAdd_Click() 
Dim rs As ADODB.Recordset 
Dim person_name As String 
Dim file_num As String 
Dim file_length As String 
Dim bytes() As Byte 
Dim num_blocks As Long 
Dim left_over As Long 
Dim block_num As Long person_name = InputBox("Name") 
If Len(person_name) = 0 Then Exit Sub dlgPicture.Flags = _ 
cdlOFNFileMustExist Or _ 
cdlOFNHideReadOnly Or _ 
cdlOFNExplorer 
dlgPicture.CancelError = True 
dlgPicture.Filter = "Graphics Files|*.bmp;*.ico;*.jpg;*.gif" On Error Resume Next 
dlgPicture.ShowOpen 
If Err.Number = cdlCancel Then 
Exit Sub 
ElseIf Err.Number <> 0 Then 
MsgBox "Error " & Format$(Err.Number) & _ 
" selecting file." & vbCrLf & Err.Description 
Exit Sub 
End If 注释: Open the picture file. 
file_num = FreeFile 
Open dlgPicture.FileName For Binary Access Read As #file_num file_length = LOF(file_num) 
If file_length > 0 Then 
num_blocks = file_length / BLOCK_SIZE 
left_over = file_length Mod BLOCK_SIZE Set rs = New ADODB.Recordset 
rs.CursorType = adOpenKeyset 
rs.LockType = adLockOptimistic 
rs.Open "Select Name, Picture, FileLength FROM People", m_DBConn rs.AddNew 
rs!Name = person_name 
rs!FileLength = file_length ReDim bytes(BLOCK_SIZE) 
For block_num = 1 To num_blocks 
Get #file_num, , bytes() 
rs!Picture.AppendChunk bytes() 
Next block_num If left_over > 0 Then 
ReDim bytes(left_over) 
Get #file_num, , bytes() 
rs!Picture.AppendChunk bytes() 
End If rs.Update 
Close #file_num lstPeople.AddItem person_name 
lstPeople.Text = person_name 
End If 
End Sub 

解决方案 »

  1.   

    '**************首先声明这是csdn以前高人吴文智的***********
    '存文件到数据库
    Const BLOCKSIZE = 4096 '每次读写块的大小Public rsBinary As New ADODB.Recordset
    Public Function AddFile(ByVal FileID As Long)
        'Return boolean to decide whether refresh files list
        Dim strBin As String * 3000
        Dim btyGet() As Byte
        Dim lngBlockIndex As Long
        Dim lngBlocks As Long
        Dim lngLastBlock As Long
        Dim lngPosition As Long
        Dim lngFileLenth As Long
        Dim lngIndex As Long
        With frmBinary.CommonDialog1
            '.InitDir = App.Path
            .Filter = "All image files&brvbar;*.bmp;*.ico;*.jpg;*.gif&brvbar;Bitmap files&brvbar;*.bmp&brvbar;Icon files&brvbar;*.ico&brvbar;All files&brvbar;*.*"
            .filename = ""
            On Error GoTo ErrorHandle
            .ShowOpen
            On Error GoTo 0
            If .filename <> "" Then
                Open .filename For Binary As #1
                lngFileLenth = LOF(1)
                
                lngPosition = 0
                
                'Get block count for loop
                lngBlocks = lngFileLenth / BLOCKSIZE
                
                'Get lngth of last block for the last read
                lngLastBlock = lngFileLenth Mod BLOCKSIZE
                TypeCode = Right(.filename, 3)
                rsBinary.AddNew
                rsBinary.Fields("typecode") = TypeCode
                
                For lngBlockIndex = 1 To lngBlocks
                    ReDim btyGet(BLOCKSIZE)
                    Get #1, , btyGet()
                    rsBinary.Fields("content").AppendChunk btyGet()
                    lngPosition = lngPosition + BLOCKSIZE
                Next            If lngLastBlock > 0 Then
                    ReDim btyGet(lngLastBlock)
                    Get #1, , btyGet()
                    rsBinary.Fields("content").AppendChunk btyGet()
                End If
                rsBinary.Fields("id") = FileID
                rsBinary.Update
                rsBinary.UpdateBatch
                Close #1
                
                AddFile = True
                MsgBox "Save finished", vbInformation
            Else
                AddFile = False
            End If
        End With
        Exit Function
    ErrorHandle:
        AddFile = False
    End Function
    '从数据库取文件出来
    Public Sub SaveFile(ByVal FileID As Long)
        Dim lngBlockCount As Long
        Dim lngLastBlock As Long
        Dim lngI As Long
        Dim btyBlock() As Byte
        Dim lngResult As Long
        If rsBinary.EOF And rsBinary.BOF Then Exit Sub
        rsBinary.Requery
        rsBinary.MoveFirst
        rsBinary.Find " id=" & FileID
        
        If Not rsBinary.EOF Then
            With frmBinary.CommonDialog1
                .filename = "TempSave" & "." & rsBinary.Fields("typecode")
                '.InitDir = App.Path
                
                'If user cancel save the goto handle
                On Error GoTo ErrorHandle
                .ShowSave
                If .filename <> "" Then
                    lngBlockCount = rsBinary.Fields("content").ActualSize \ BLOCKSIZE
                    lngLastBlock = rsBinary.Fields("content").ActualSize Mod BLOCKSIZE
                    
                    If Dir(.filename) <> "" Then
                        If MsgBox("File " & .filename & " is exist,overwrite?", vbYesNo + vbQuestion) = vbYes Then
                            Kill .filename
                        Else
                            Exit Sub
                        End If
                    Else
                    End If
                        
                    Open .filename For Binary As #1
                    
                    ReDim btyBinary(BLOCKSIZE)
                    
                    For lngI = 1 To lngBlockCount
                        btyBlock() = rsBinary.Fields("content").GetChunk(BLOCKSIZE)
                        Put #1, , btyBlock
                    Next
                    
                    If lngLastBlock <> 0 Then
                        ReDim btyBlock(lngLastBlock)
                        btyBlock() = rsBinary.Fields("content").GetChunk(lngLastBlock)
                        Put #1, , btyBlock
                    End If
                    
                    Close #1
                    MsgBox .filename & " is saved", vbInformation
                Else
                End If
            End With
        End If
        
        Exit Sub
    ErrorHandle:
        
    End Sub
      

  2.   

    '
    Public Sub P_Open()
        With rsBinary
            If .State = adStateOpen Then
                .Close
            End If
            .ActiveConnection = adoCN
            .CursorLocation = adUseClient
            .CursorType = adOpenDynamic
            .LockType = adLockBatchOptimistic
            .Source = "SELECT * FROM sss"                        'sss库字段id ,content,typecode
            .Open
        End WithEnd Sub
      

  3.   

    '***************************************************************
    '* Save/Retrieve Image Data From SQL Server DataBase Using
    '* ADOStream Objects.
    '*************************************************************** 
    '* Code By: Michael P. Gerety
    '***************************************************************Dim rstRecordset As ADODB.Recordset
    Dim cnnConnection As ADODB.Connection
    Dim strStream As ADODB.Stream'以下在窗体中
    '*Setup:
    '*Create a form and place 3 command buttons named:
    '*cmdLoad, cmdSelectSave, and cmdClear
    '*Place a CommonDialog Control Named Dialog
    '*Place an ImageBox (or PictureBox) named Image1
    '** The field type in Sql Server must be "Image"
    '** Everywhere you see "***" in the code is where you must enter 
    '** your own data.Private Sub cmdClear_Click()
        Image1.Picture = Nothing
        
    End SubPrivate Sub cmdLoad_Click()
        If Not LoadPictureFromDB(rstRecordset) Then
            MsgBox "Invalid Data Or No Picture In DB"
        End If
    End SubPrivate Sub cmdSelectSave_Click()
        'Open Dialog Box
        With dlgDialog
            .DialogTitle = "Open Image File...."
            .Filter = "Image Files (*.gif; *.bmp)| *.gif;*.bmp"
            .CancelError = True
    procReOpen:
             .ShowOpen
             
            If .FileName = "" Then
                MsgBox "Invalid filename or file not found.", _
                    vbOKOnly + vbExclamation, "Oops!"
                GoTo procReOpen
            Else
                If Not SavePictureToDB(rstRecordset, .FileName) Then
                    MsgBox "Save was unsuccessful :(", vbOKOnly + _
                            vbExclamation, "Oops!"
                    Exit Sub
                End If
            End If
                
        End With
    End SubPrivate Sub Form_Load()
        Set cnnConnection = New ADODB.Connection
        Set rstRecordset = New ADODB.Recordset    cnnConnection.Open ("Provider=SQLOLEDB; " & _
            "data Source=**YourServer**;" & _
            "Initial Catalog=**YourDatabase**; " & _
            "User Id=**YourUID**;Password=***YourPass***")
        rstRecordset.Open "Select * from YourTable", cnnConnection, _
             adOpenKeyset, adLockOptimistic
        End Sub
    Public Function LoadPictureFromDB(RS As ADODB.Recordset)    On Error GoTo procNoPicture
        
        'If Recordset is Empty, Then Exit
        If RS Is Nothing Then
            GoTo procNoPicture
        End If
        
        Set strStream = New ADODB.Stream
        strStream.Type = adTypeBinary
        strStream.Open
        
        strStream.Write RS.Fields("**YourImageField**").Value    
        strStream.SaveToFile "C:\Temp.bmp", adSaveCreateOverWrite
        Image1.Picture = LoadPicture("C:\Temp.bmp")
        Kill ("C:\Temp.bmp")
        LoadPictureFromDB = TrueprocExitFunction:
        Exit Function
    procNoPicture:
        LoadPictureFromDB = False
        GoTo procExitFunction
    End FunctionPublic Function SavePictureToDB(RS As ADODB.Recordset, _
        sFileName As String)    On Error GoTo procNoPicture
        Dim oPict As StdPicture
        
        Set oPict = LoadPicture(sFileName)
        
        'Exit Function if this is NOT a picture file
        If oPict Is Nothing Then
            MsgBox "Invalid Picture File!", vbOKOnly, "Oops!"
            SavePictureToDB = False
            GoTo procExitSub
        End If
        
        RS.AddNew
            Set strStream = New ADODB.Stream
        strStream.Type = adTypeBinary
        strStream.Open
        strStream.LoadFromFile sFileName
        RS.Fields("***YourImageField***").Value = strStream.Read
        
        Image1.Picture = LoadPicture(sFileName)
        SavePictureToDB = True
        
        procExitSub:
        Exit Function
    procNoPicture:
        SavePictureToDB = False
        GoTo procExitSub
    End Function