用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.   

    我们在编写应用程序的时候,经常向数据库中读写图片。数据库中的图片操作有几种方式。
    1.将图片控件与Data控件帮定
    2.通过代码来进行操作
    第一种方法大家经常会在互联网上查到,本文主要介绍第二种方法。
    应用的数据库是Access或SQL Server.一 建立数据库
       Access数据库中的图片字段选择的类型为Ole 对象,可以向该字段写入二进制数据
       SQL Server 数据库图片字段选择类型为image 或 varbinary。二 写入图片
       从图片文件读取文件的内容,直接写入对应的图片字段,应用字段的AppendChunk方法。代码如下:
       
    Pulic Function SaveImageToDatabase(ByVal FileName As String, fField As Field) As Boolean
      
        Dim DataFile As Integer
        Dim Chunks As Integer
        Dim Fragment As Integer
        Dim lLen As Long
        Dim Chunk() As Byte
        Dim i As Integer
        Const ChunkSize As Integer = 4096
     
        DataFile = FreeFile()
             Open FileName For Binary Access Read As DataFile
             lLen = LOF(DataFile)            
             If lLen = 0 Then
            Close DataFile
            SaveImageToDatabase = False
            Exit Function
        Else
            Chunks = lLen \ ChunkSize
            Fragment = lLen Mod ChunkSize
                    ReDim Chunk(Fragment)
            Get DataFile, , Chunk
            fField.AppendChunk Chunk
                    ReDim Chunk(ChunkSize)
            For i = 1 To Chunks
                Get DataFile, , Chunk
                fField.AppendChunk Chunk
            Next i        
            Close DataFile
        End If
        SaveImageToDatabase = True
    End Function三 读取图片
       从对应的图片字段中读取字段的内容,写入到一个图片文件中。应用了字段的GetChunk方法。代码如下: Public Function DisplayImageFromDatabase(ByRef FileName As String, fField As Field) As Boolean     Dim DataFile As Integer
        Dim Chunks As Integer
        Dim Fragment As Integer
        Dim lLen As Long
        Dim Chunk() As Byte
        Dim i As Integer
             Dim fos As New Scripting.FileSystemObject
        Dim tfolder As Folder
        Dim tfile As String
        Dim TemporaryFolder As String
        
        if FileName="" then    
        Set tfolder = fos.GetSpecialFolder(2)    '取得系统临时文件夹
        TemporaryFolder = tfolder.Path
        tfile = fos.GetTempName()               
        tfile = Left(tfile, Len(tfile) - 3)     
        tfile = tfile & "BMP" 
        FileName = TemporaryFolder & "\" & tfile
        end if
        Const ChunkSize As Integer = 4096
             lLen = fField.ActualSize
             If lLen = 0 Then
            DisplayImageFromDatabase = False
             FileName = ""
            Exit Function
               End If
             DataFile = FreeFile()
             Open FileName For Binary Access Write As DataFile
             Chunks = lLen \ ChunkSize
        Fragment = lLen Mod ChunkSize
        ReDim Chunk(Fragment)
        Chunk() = fField.GetChunk(Fragment)
        Put DataFile, , Chunk()
        For i = 1 To Chunks
            Chunk() = fField.GetChunk(ChunkSize)
            Put DataFile, , Chunk()
              Next i
             Close DataFile
       DisplayImageFromDatabase = True
    End Function四 调用上述两个函数的方法
         数据表名称是Stamp,其中有两个字段 sta_ID,sta_Image.  字段sta_Image是图片字段。     1 写入图片
    Private Sub SavePicture(ByVal ID As Long, ByVal sFile As String)
       Dim sSQL As String
       Dim recX As New ADODB.Recordset
       sSQL = "Select sta_Image from stamp Where sta_ID=" & ID
       recX.Open sSQL, cn, adOpenDynamic, adLockOptimistic
       SaveImageToDatabase sFile, recX.Fields(0)
       recX.UpdateBatch adAffectCurrent
       recX.Close
    End Sub
     
         2 显示图片
    Private Sub ShowImage(byval lID as long)
       Dim b As Boolean
       Dim ssql As String
       Dim recX As New ADODB.Recordset      
        
               b=False 
               ssql = "Select sta_Image From stamp Where sta_ID=" & lID
       recX.Open ssql, cn, adOpenDynamic
       Dim sFile As String
       b = DisplayImageFromDataBase(sFile, recX.Fields(0))
       recX.Close    If b = True Then
          Set Picture1.Picture = LoadPicture(sFile)
       Else
          Picture1.Cls
       End If
       Picture1.Refresh
    End Sub
      

  2.   

    太长了吧,用API不过二十行啊