how to save and load images to and from a database

Option Explicit

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
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

'Purpose : Saves pictures in image boxes (or similiar) to a field in a recordset
'Inputs : oPictureControl A control containing an image
' adoRS ADO recordset to add the image to
' sFieldName The field name in adoRS, to add the image to
'Outputs : Returns True if succeeded in updating the recordset
'Notes : The field specified in sFieldName, must have a binary field type (ie. OLE Object in access)
' Save the image at the currect cursor location in the recordset.
'Revisions :

Public Function SavePictureToDB(oPictureControl As Object, adoRS As ADODB.Recordset, sFieldName As String) As Boolean
Dim oPict As StdPicture
Dim sDir As String, sTempFile As String
Dim iFileNum As Integer
Dim lFileLength As Long
Dim abBytes() As Byte
Dim iCtr As Integer

On Error GoTo ErrHandler

Set oPict = oPictureControl.Picture
If oPict Is Nothing Then
SavePictureToDB = False
Exit Function
End If

'Save picture to temp file
sTempFile = FileGetTempName
SavePicture oPict, sTempFile

'read file contents to byte array
iFileNum = FreeFile
Open sTempFile For Binary Access Read As #iFileNum
lFileLength = LOF(iFileNum)
ReDim abBytes(lFileLength)
Get #iFileNum, , abBytes()
'put byte array contents into db field
adoRS.Fields(sFieldName).AppendChunk abBytes()
Close #iFileNum

'Don't return false if file can't be deleted
On Error Resume Next
Kill sTempFile
SavePictureToDB = True
Exit Function

ErrHandler:
SavePictureToDB = False
Debug.Print Err.Description
End Function


'Purpose : Loads a Picture, saved as binary data in a database, from a recordset into a picture control.
'Inputs : oPictureControl A control to load the image into
' adoRS ADO recordset to add the image to
' sFieldName The field name in adoRS, to add the image to
'Outputs : Returns True if succeeded in loading the image
'Notes : Loads the image at the currect cursor location in the recordset.


Public Function LoadPictureFromDB(oPictureControl As Object, adoRS As ADODB.Recordset, sFieldName As String) As Boolean
Dim oPict As StdPicture
Dim sDir As String
Dim sTempFile As String
Dim iFileNum As Integer
Dim lFileLength As Long
Dim abBytes() As Byte
Dim iCtr As Integer

On Error GoTo ErrHandler
sTempFile = FileGetTempName

iFileNum = FreeFile
Open sTempFile For Binary As #iFileNum
lFileLength = LenB(adoRS(sFieldName))

abBytes = adoRS(sFieldName).GetChunk(lFileLength)
Put #iFileNum, , abBytes()
Close #iFileNum

oPictureControl.Picture = LoadPicture(sTempFile)

Kill sTempFile
LoadPictureFromDB = True
Exit Function

ErrHandler:
LoadPictureFromDB = False
Debug.Print Err.Description
End Function


'Purpose : The FileGetTempName function returns a name of a temporary file.
'Inputs : [sFilePrefix] The prefix of the file name.
'Outputs : Returns the name of the next free temporary file name (and path).
'Notes : The filename is the concatenation of specified path and prefix strings,
' a hexadecimal string formed from a specified integer, and the .TMP extension


Function FileGetTempName(Optional sFilePrefix As String = "TMP") As String
Dim sTemp As String * 260, lngLen As Long
Static ssTempPath As String

If LenB(ssTempPath) = 0 Then
'Get the temporary path
lngLen = GetTempPath(260, sTemp)
'strip the rest of the buffer
ssTempPath = Left$(sTemp, lngLen)
If Right$(ssTempPath, 1) <> "\" Then
ssTempPath = ssTempPath & "\"
End If
End If

'Get a temporary filename
lngLen = GetTempFileName(ssTempPath, sFilePrefix, 0, sTemp)
'Remove all the unnecessary chr$(0)'s
FileGetTempName = Left$(sTemp, InStr(1, sTemp, Chr$(0)) - 1)
End Function


'SAMPLE USAGE
'NOTE : Add a PictureBox control to a form before running this code
Sub TestLoadPicture()
Dim sConn As String
Dim oConn As New ADODB.Connection
Dim oRs As New ADODB.Recordset

On Error GoTo ErrFailed
sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyDb.MDB;Persist Security Info=False"

oConn.Open sConn
oRs.Open "SELECT * FROM MyTable", oConn, adOpenKeyset, adLockOptimistic
If oRs.EOF = False Then
LoadPictureFromDB Picture1, oRs, "MyFieldName"
End If
oRs.Close
Exit Sub
ErrFailed:
MsgBox "Error " & Err.Description
End Sub

'SAMPLE USAGE
'NOTE : Add a PictureBox control to a form before running this code
Sub TestSavePicture()
Dim sConn As String
Dim oConn As New ADODB.Connection
Dim oRs As New ADODB.Recordset

On Error GoTo ErrFailed
sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyDb.MDB;Persist Security Info=False"

oConn.Open sConn
oRs.Open "SELECT * FROM MYTABLE", oConn, adOpenKeyset, adLockOptimistic
If oRs.EOF = False Then
oRs.AddNew
SavePictureToDB Picture1, oRs, "MYFIELD"
oRs.Update
End If
oRs.Close
Exit Sub
ErrFailed:
MsgBox "Error " & Err.Description
End Sub

No comments:

Visual Basic-6 has emerged as one of the standard Windows Programming Language and it has become a must for all Software people for developing Applications in Visual Environment. So it is, one must learn Visual Basic-6.

What is our Objective in this Courseware?


The Overall Objective in this Courseware is to give a Hands-on Approach to develop different projects in Visual Basic-6.0 using intrinsic, professional and user–created ActiveX controls and also develop projects using databases, DAO’s, ADO’s, DLL’s, Documents, Crystal Reports etc. covering almost all the essential features of VB-6 Professional Edition. After reading one lesson any interested reader will be able to get complete hands-on experience with the VB project and get a sense of fulfilment and achievement. Learning by doing is the motto with which this courseware is written. After giving a short introduction about VB-6 we will explain how to create and execute a project in VB using some intrinsic ActiveX controls. Creating and executing projects will be the central theme of all the lessons which we will be giving in this courseware.

What is Visual Basic-6?


Visual Basic-6 has its origin in Basic which was developed round about the year 1960, when high level languages were just being introduced to the computer community. Microsoft has made it extremely powerful by gearing all its good features to the Windows environment. Starting with the version 3 and then with 4, and then with 6, Visual Basic is now at version 6. Basic is a Procedure Oriented Language intended to implement single tasks in text based environment whereas Visual Basic is an Event Driven Language intended to implement Projects or Applications containing multiple tasks in Windows Environment.

What can Visual Basic do for you?

Visual Basic can serve as an ideal front end tool for the clients to interact. It has got connectivity mechanisms for all types of databases situated far and wide in a network and so it can cater to the needs of a large body of clients. Using the latest ActiveX technologies, it can integrate the functionalities provided by other applications like Word Excel and other Windows. Its internet capabilities provide easy access to documents and applications across the internet. Above all it embodies the Object Oriented Technology, which is the cutting edge technology for all the present day developments in the Software World. The final application is a true EXE file and so can be freely distributed.


Structure of VB-6 Projects:


We said earlier that VB-6 implements projects or applications. A project is developed using one or more Forms. A Form is simply a window containing one or more Controls. Controls in VB consist of labels, text boxes, list boxes, combo boxes, scroll bars etc. which are the constituents of windows environment. It is only the controls that give VB, its immense power and so there is a lot of interest in creating more and more powerful controls. ActiveX controls mark a significant development in controls technology. In fact all controls in VB-6 are ActiveX controls, which have the extension .ocx. These controls have properties whose values can be initialized at design time and also varied during run time. The properties are something like variables. The controls are activated by codes written in a high level language. By associating our problem variables with the properties of the controls, our problem variables can be manipulated to give the problem solution. In summary we can say that a VB project is made of forms, controls and their properties and codes.

Integrated Development Environment:

The working environment in VB is often referred to as the Integrated Development Environment or IDE, because it integrates many different functions such as design, editing, compiling and debugging within a common environment. Since all our projects are developed only in the IDE, let us now have a brief look at its features. You will be able to understand their uses at the time of building projects. The VB IDE looks as shown in the figure.