tomhoran
asked on
Display an image from SQL database
i've been read this and that about doing this. Any one out there have any code they want to share that will real an image from a SQL database and then dispay it on a webpage ....
the ado stream look interesting...
the ado stream look interesting...
OK, let's say you've got this table, "images", and it stores only GIFs in a binary column called "data". And, of course, a uniqueidentifier Primary Key, "id". Let's assume that you have a global ConnectionString (NOT an ADO Connection object!) stored in a Session variable.
Next, you create a page called "image.asp", and pass it the image ID. "Image.asp" will look kinda like this:
<%@ Language=VBScript %><%
Dim ID, Item
Set Item=Request.QueryString(" ID")
If Item.Count Then ID="" & Item(1)
With Server.CreateObject("ADODB .Recordset ")
.Open "[images] WHERE [id]='" & ID & "'", _
Session("ConnectionString" )
If .EOF Then
'Image isn't there - you could send a default image
Else 'Found image - send it to the browser
Response.ContentType="imag e/gif"
Response.BinaryWrite .Fields("data")
End If
.Close
End With
%>
Now, on our target page, we have our image tag:
<IMG src="image.asp?ID={OICU-81 2...}">
Voila!
Next, you create a page called "image.asp", and pass it the image ID. "Image.asp" will look kinda like this:
<%@ Language=VBScript %><%
Dim ID, Item
Set Item=Request.QueryString("
If Item.Count Then ID="" & Item(1)
With Server.CreateObject("ADODB
.Open "[images] WHERE [id]='" & ID & "'", _
Session("ConnectionString"
If .EOF Then
'Image isn't there - you could send a default image
Else 'Found image - send it to the browser
Response.ContentType="imag
Response.BinaryWrite .Fields("data")
End If
.Close
End With
%>
Now, on our target page, we have our image tag:
<IMG src="image.asp?ID={OICU-81
Voila!
Hi tomhoran,
DISPLAYING IMAGES FROM DATABASE
How can I display images that reside in my database through an ASP page?
http://www.aspfaqs.com/ASPScripts/PrintFAQ.asp?FAQID=172
Displaying Images that Reside in a Database
http://www.4guysfromrolla.com/webtech/060100-1.shtml
HOWTO: Display an Image on a Web Page When the Path Is Stored in a Database
http://support.microsoft.com/default.aspx?scid=KB;en-us;q299320
HOWTO: Display Images Stored in a BLOB Field
http://support.microsoft.com/default.aspx?scid=KB;en-us;q173308
Store Images in Your Database
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvbpj01/html/gs0102.asp
Storing Images in a DB - Pros and Cons
http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=10477
If you have any follow-up questions, feel free to post here.
Best Regards,
>apollois<
DISPLAYING IMAGES FROM DATABASE
How can I display images that reside in my database through an ASP page?
http://www.aspfaqs.com/ASPScripts/PrintFAQ.asp?FAQID=172
Displaying Images that Reside in a Database
http://www.4guysfromrolla.com/webtech/060100-1.shtml
HOWTO: Display an Image on a Web Page When the Path Is Stored in a Database
http://support.microsoft.com/default.aspx?scid=KB;en-us;q299320
HOWTO: Display Images Stored in a BLOB Field
http://support.microsoft.com/default.aspx?scid=KB;en-us;q173308
Store Images in Your Database
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvbpj01/html/gs0102.asp
Storing Images in a DB - Pros and Cons
http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=10477
If you have any follow-up questions, feel free to post here.
Best Regards,
>apollois<
Take this from MSDN. It might help you.
Anyway it not advisable to store images in database. It is better to store the path and retieve it.
AppendChunk and GetChunk Methods Example (VB)
This example uses the AppendChunk and GetChunk methods to fill an image field with data from another record.
'BeginAppendChunkVB
'To integrate this code
'replace the data source and initial catalog values
'in the connection string
Public Sub AppendChunkX()
'recordset and connection variables
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim rstPubInfo As ADODB.Recordset
Dim strSQLPubInfo As String
'record variables
Dim strPubID As String
Dim strPRInfo As String
Dim lngOffset As Long
Dim lngLogoSize As Long
Dim varLogo As Variant
Dim varChunk As Variant
Dim strMsg As String
Const conChunkSize = 100
' Open a connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider=sqloledb;Data Source=MyServer;Initial Catalog=Pubs;User Id=sa;Password=; "
Cnxn.Open strCnxn
' Open the pub_info table with a cursor that allows updates
Set rstPubInfo = New ADODB.Recordset
strSQLPubInfo = "pub_info"
rstPubInfo.Open strSQLPubInfo, Cnxn, adOpenKeyset, adLockOptimistic, adCmdTable
' Prompt for a logo to copy
strMsg = "Available logos are : " & vbCr & vbCr
Do While Not rstPubInfo.EOF
strMsg = strMsg & rstPubInfo!pub_id & vbCr & _
Left(rstPubInfo!pr_info, InStr(rstPubInfo!pr_info, ",") - 1) & _
vbCr & vbCr
rstPubInfo.MoveNext
Loop
strMsg = strMsg & "Enter the ID of a logo to copy:"
strPubID = InputBox(strMsg)
' Copy the logo to a variable in chunks
rstPubInfo.Filter = "pub_id = '" & strPubID & "'"
lngLogoSize = rstPubInfo!logo.ActualSize
Do While lngOffset < lngLogoSize
varChunk = rstPubInfo!logo.GetChunk(c onChunkSiz e)
varLogo = varLogo & varChunk
lngOffset = lngOffset + conChunkSize
Loop
' Get data from the user
strPubID = Trim(InputBox("Enter a new pub ID" & _
" [must be > 9899 & < 9999]:"))
strPRInfo = Trim(InputBox("Enter descriptive text:"))
' Add the new publisher to the publishers table to avoid
' getting an error due to foreign key constraint
Cnxn.Execute "INSERT publishers(pub_id, pub_name) VALUES('" & _
strPubID & "','Your Test Publisher')"
' Add a new record, copying the logo in chunks
rstPubInfo.AddNew
rstPubInfo!pub_id = strPubID
rstPubInfo!pr_info = strPRInfo
lngOffset = 0 ' Reset offset
Do While lngOffset < lngLogoSize
varChunk = LeftB(RightB(varLogo, lngLogoSize - lngOffset), _
conChunkSize)
rstPubInfo!logo.AppendChun k varChunk
lngOffset = lngOffset + conChunkSize
Loop
rstPubInfo.Update
' Show the newly added data
MsgBox "New record: " & rstPubInfo!pub_id & vbCr & _
"Description: " & rstPubInfo!pr_info & vbCr & _
"Logo size: " & rstPubInfo!logo.ActualSize
' Delete new records because this is a demo
rstPubInfo.Requery
Cnxn.Execute "DELETE FROM pub_info " & _
"WHERE pub_id = '" & strPubID & "'"
Cnxn.Execute "DELETE FROM publishers " & _
"WHERE pub_id = '" & strPubID & "'"
' clean up
rstPubInfo.Close
Cnxn.Close
Set rstPubInfo = Nothing
Set Cnxn = Nothing
End Sub
'EndAppendChunkVB
Anyway it not advisable to store images in database. It is better to store the path and retieve it.
AppendChunk and GetChunk Methods Example (VB)
This example uses the AppendChunk and GetChunk methods to fill an image field with data from another record.
'BeginAppendChunkVB
'To integrate this code
'replace the data source and initial catalog values
'in the connection string
Public Sub AppendChunkX()
'recordset and connection variables
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim rstPubInfo As ADODB.Recordset
Dim strSQLPubInfo As String
'record variables
Dim strPubID As String
Dim strPRInfo As String
Dim lngOffset As Long
Dim lngLogoSize As Long
Dim varLogo As Variant
Dim varChunk As Variant
Dim strMsg As String
Const conChunkSize = 100
' Open a connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider=sqloledb;Data Source=MyServer;Initial Catalog=Pubs;User Id=sa;Password=; "
Cnxn.Open strCnxn
' Open the pub_info table with a cursor that allows updates
Set rstPubInfo = New ADODB.Recordset
strSQLPubInfo = "pub_info"
rstPubInfo.Open strSQLPubInfo, Cnxn, adOpenKeyset, adLockOptimistic, adCmdTable
' Prompt for a logo to copy
strMsg = "Available logos are : " & vbCr & vbCr
Do While Not rstPubInfo.EOF
strMsg = strMsg & rstPubInfo!pub_id & vbCr & _
Left(rstPubInfo!pr_info, InStr(rstPubInfo!pr_info, ",") - 1) & _
vbCr & vbCr
rstPubInfo.MoveNext
Loop
strMsg = strMsg & "Enter the ID of a logo to copy:"
strPubID = InputBox(strMsg)
' Copy the logo to a variable in chunks
rstPubInfo.Filter = "pub_id = '" & strPubID & "'"
lngLogoSize = rstPubInfo!logo.ActualSize
Do While lngOffset < lngLogoSize
varChunk = rstPubInfo!logo.GetChunk(c
varLogo = varLogo & varChunk
lngOffset = lngOffset + conChunkSize
Loop
' Get data from the user
strPubID = Trim(InputBox("Enter a new pub ID" & _
" [must be > 9899 & < 9999]:"))
strPRInfo = Trim(InputBox("Enter descriptive text:"))
' Add the new publisher to the publishers table to avoid
' getting an error due to foreign key constraint
Cnxn.Execute "INSERT publishers(pub_id, pub_name) VALUES('" & _
strPubID & "','Your Test Publisher')"
' Add a new record, copying the logo in chunks
rstPubInfo.AddNew
rstPubInfo!pub_id = strPubID
rstPubInfo!pr_info = strPRInfo
lngOffset = 0 ' Reset offset
Do While lngOffset < lngLogoSize
varChunk = LeftB(RightB(varLogo, lngLogoSize - lngOffset), _
conChunkSize)
rstPubInfo!logo.AppendChun
lngOffset = lngOffset + conChunkSize
Loop
rstPubInfo.Update
' Show the newly added data
MsgBox "New record: " & rstPubInfo!pub_id & vbCr & _
"Description: " & rstPubInfo!pr_info & vbCr & _
"Logo size: " & rstPubInfo!logo.ActualSize
' Delete new records because this is a demo
rstPubInfo.Requery
Cnxn.Execute "DELETE FROM pub_info " & _
"WHERE pub_id = '" & strPubID & "'"
Cnxn.Execute "DELETE FROM publishers " & _
"WHERE pub_id = '" & strPubID & "'"
' clean up
rstPubInfo.Close
Cnxn.Close
Set rstPubInfo = Nothing
Set Cnxn = Nothing
End Sub
'EndAppendChunkVB
ASKER
jSkipB .. Thanks.
that's excatly what i'm doing. I wonder if my upload of the image isn;t working right. Here is my code for that:
Set UploadedInfo = Server.CreateObject("aspSm artUpload. SmartUploa d")
set RepayMeData = Server.CreateObject("Repay MeData.Get Data")
set RepayMeFuns = Server.CreateObject("Repay MeFuns.Loa dImage")
compno = ""
descrip = ""
whichsiglist = ""
UploadedInfo.Upload
itemcnt = UploadedInfo.Form.Count
for x = 1 to itemcnt
itemname = UploadedInfo.Form.Item(x). Name
itemvalue = UploadedInfo.Form.Item(x). Values
if UploadedInfo.Form.Item(x). Name = "descrip" then
descrip = UploadedInfo.Form.Item(x). Values
end if
if UploadedInfo.Form.Item(x). Name = "whichsig_list" then
whichsiglist = UploadedInfo.Form.Item(x). Values
end if
if UploadedInfo.Form.Item(x). Name = "compno" then
compno = UploadedInfo.Form.Item(x). Values
end if
next
FileSize = UploadedInfo.Files.Item(1) .Size
Signaturedata = UploadedInfo.Files.Item(1) .ContentSt ring
UploadedInfo.Files.Item(1) .SaveAs "c:\wk2\testupld.jpg"
'new signature?
if whichsiglist = "N" then
ColNames = "cust_no,description"
ColValues = "'" & CntlParms(LogCustNo_) & "','" & _
replace(descrip, "'", "''") & "'"
DefinedSel = "set nocount on "
DefinedSel = DefinedSel & "insert signatures(" & ColNames & ") values (" & ColValues & ") "
DefinedSel = DefinedSel & "select @@identity AS 'Id' "
DefinedSel = DefinedSel & "set nocount off "
Set SignatureRecSet = RepayMeData.GetData("", "", DefinedSel, AddlParms, "", "", adOpenStatic, adLockOptimistic, ErrorMsg)
whichsiglist = SignatureRecSet("Id").valu e
end if
DefinedSel = "select signature from signatures where signature_id = " & _
whichsiglist
Set SignatureRecSet = RepayMeData.GetData("", "", DefinedSel, AddlParms, "", "", adOpenStatic, adLockOptimistic, ErrorMsg)
DefinedSel = ""
Colname = "signature"
xx=RepayMeFuns.LoadImage(S ignatureRe cSet, Colname, Signaturedata)
SignatureRecSet.update
here is the code for RepayMeFuns.LoadImage:
Public Function LoadImage(TheRecordSet As Variant, TheColumn As Variant, ImageData As Variant) As Variant
TheRecordSet(TheColumn).Ap pendChunk (ImageData)
TheRecordSet.Update
LoadImage = 1
End Function
When i look at the table using query analyzer i can see hex data in the image column.
Suggestions?
that's excatly what i'm doing. I wonder if my upload of the image isn;t working right. Here is my code for that:
Set UploadedInfo = Server.CreateObject("aspSm
set RepayMeData = Server.CreateObject("Repay
set RepayMeFuns = Server.CreateObject("Repay
compno = ""
descrip = ""
whichsiglist = ""
UploadedInfo.Upload
itemcnt = UploadedInfo.Form.Count
for x = 1 to itemcnt
itemname = UploadedInfo.Form.Item(x).
itemvalue = UploadedInfo.Form.Item(x).
if UploadedInfo.Form.Item(x).
descrip = UploadedInfo.Form.Item(x).
end if
if UploadedInfo.Form.Item(x).
whichsiglist = UploadedInfo.Form.Item(x).
end if
if UploadedInfo.Form.Item(x).
compno = UploadedInfo.Form.Item(x).
end if
next
FileSize = UploadedInfo.Files.Item(1)
Signaturedata = UploadedInfo.Files.Item(1)
UploadedInfo.Files.Item(1)
'new signature?
if whichsiglist = "N" then
ColNames = "cust_no,description"
ColValues = "'" & CntlParms(LogCustNo_) & "','" & _
replace(descrip, "'", "''") & "'"
DefinedSel = "set nocount on "
DefinedSel = DefinedSel & "insert signatures(" & ColNames & ") values (" & ColValues & ") "
DefinedSel = DefinedSel & "select @@identity AS 'Id' "
DefinedSel = DefinedSel & "set nocount off "
Set SignatureRecSet = RepayMeData.GetData("", "", DefinedSel, AddlParms, "", "", adOpenStatic, adLockOptimistic, ErrorMsg)
whichsiglist = SignatureRecSet("Id").valu
end if
DefinedSel = "select signature from signatures where signature_id = " & _
whichsiglist
Set SignatureRecSet = RepayMeData.GetData("", "", DefinedSel, AddlParms, "", "", adOpenStatic, adLockOptimistic, ErrorMsg)
DefinedSel = ""
Colname = "signature"
xx=RepayMeFuns.LoadImage(S
SignatureRecSet.update
here is the code for RepayMeFuns.LoadImage:
Public Function LoadImage(TheRecordSet As Variant, TheColumn As Variant, ImageData As Variant) As Variant
TheRecordSet(TheColumn).Ap
TheRecordSet.Update
LoadImage = 1
End Function
When i look at the table using query analyzer i can see hex data in the image column.
Suggestions?
Suggestion : Do NOT store binary in your database. It makes your database far too big, especially if you are storing multiple images in it.
Wakie.
Wakie.
ASKER
Wakie,
I'm only storing signatures in the database and there won't be many.
i'm doing it for security reasons, i don't want to store the images on a hard drive.
I'm only storing signatures in the database and there won't be many.
i'm doing it for security reasons, i don't want to store the images on a hard drive.
tomhoran,
The hex visible from Query Analyzer is a good thing - it means your data is being stored properly, in binary format. What I didn't notice, though, and I may have missed it, is, setting the content type for the Response.
You'll notice in my example that I set Response.ContentType to "image/gif" - which only works for GIF images. However, in your example, you show a JPEG image. So, most likely, your upload control has a property of its File object that tells you the content type. You're best bet is to make sure you have a column in your table for the content type, and store whatever the Upload's File object's content type property contains (I'm not familiar with the particular controls you're using, so I'll try to wing it):
Colname = "content_type"
Colvalue = Upload.File(1).ContentType
'[Set "content_type" column]
SignatureRecSet.update
Then, to display it with my code (way above), substitute:
Response.ContentType=.Fiel ds("conten t_type")
And don't worry too much about storing a modest amount of binary data in your database.
That should do it. I'm a little burnt today, so keep me posted,
Skip
P.S. If you decide to go with those VB examples, better remove all those " As Variant" type declarations...
The hex visible from Query Analyzer is a good thing - it means your data is being stored properly, in binary format. What I didn't notice, though, and I may have missed it, is, setting the content type for the Response.
You'll notice in my example that I set Response.ContentType to "image/gif" - which only works for GIF images. However, in your example, you show a JPEG image. So, most likely, your upload control has a property of its File object that tells you the content type. You're best bet is to make sure you have a column in your table for the content type, and store whatever the Upload's File object's content type property contains (I'm not familiar with the particular controls you're using, so I'll try to wing it):
Colname = "content_type"
Colvalue = Upload.File(1).ContentType
'[Set "content_type" column]
SignatureRecSet.update
Then, to display it with my code (way above), substitute:
Response.ContentType=.Fiel
And don't worry too much about storing a modest amount of binary data in your database.
That should do it. I'm a little burnt today, so keep me posted,
Skip
P.S. If you decide to go with those VB examples, better remove all those " As Variant" type declarations...
ASKER
jSkipB,
Why should i get rid of the As Variant type declarations. Since i'm calling this from an ASp page and ASP types are Variant if i don't declare them as that the call fails.
I can get the window/screen to display and you can see that there is an image there, i.e. there is a box the size of the image, but the image doesn;t display. Its just an out line with a box with a red x in the upper left corrner.
Ideas?
I'm wondering if i need to do some else with the image string before it's stored into the database? this is what i see:
0xFF00D800FF00E00000001000 4A00460049 0046000000 0100010000 0000000100 0000010000 000000FF00 DB00000043 0000000300 0200020003 0002000200 0300030003 0003000400 0300030004 0005000800 0500050004 0004000500 0A00070007 0006000800 0C000A000C 000C000B00 0A000B000B 000D000E00 120010000D
Why should i get rid of the As Variant type declarations. Since i'm calling this from an ASp page and ASP types are Variant if i don't declare them as that the call fails.
I can get the window/screen to display and you can see that there is an image there, i.e. there is a box the size of the image, but the image doesn;t display. Its just an out line with a box with a red x in the upper left corrner.
Ideas?
I'm wondering if i need to do some else with the image string before it's stored into the database? this is what i see:
0xFF00D800FF00E00000001000
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
jSkipB,
The data column in the SQL database is "image" not binary, is that a problem?
The ASP program calls a VB DLL called "LoadImage". This code takes the passed recordset and uploaded image and then uses the AppendChunk method to load the image (which is passed in a Variant type variable) into the database/recordset.
The upload control does have a binary option, i wonder if that would make a difference?:
The BinaryData property contains the byte corresponding to the table index containing the transmitted data.
Syntax
.BinaryData (lngIndex)
Return Value
Returns a byte value.
Parameter
lngIndex is an index of the byte's array.
Example
<%
for i=0 to MyUpload.Files.Item(2).siz e - 1
Response.Write( Chr( MyUpLoad.Files.Item(2).Bin aryData(My Index) ) )
next i
%>
The data column in the SQL database is "image" not binary, is that a problem?
The ASP program calls a VB DLL called "LoadImage". This code takes the passed recordset and uploaded image and then uses the AppendChunk method to load the image (which is passed in a Variant type variable) into the database/recordset.
The upload control does have a binary option, i wonder if that would make a difference?:
The BinaryData property contains the byte corresponding to the table index containing the transmitted data.
Syntax
.BinaryData (lngIndex)
Return Value
Returns a byte value.
Parameter
lngIndex is an index of the byte's array.
Example
<%
for i=0 to MyUpload.Files.Item(2).siz
Response.Write( Chr( MyUpLoad.Files.Item(2).Bin
next i
%>
ASKER
could it be the way i have the form setup to do the upload?
i'm using the form definition.
<FORM ENCTYPE="multipart/form-da ta" action="./checksetup3.asp" method="post" id="thisForm" name="thisForm" ONSUBMIT="return editform();">
i'm using the form definition.
<FORM ENCTYPE="multipart/form-da
ASKER
ISkipB,
Thanks for all of the effort, could get it to work but didn't find a aspsmartupload control/method that loaded the image and it worked ...
UploadedInfo.Files.Item(1) .FileToFie ld SignatureRecSet("signature ")
A for effort!!
Thanks for all of the effort, could get it to work but didn't find a aspsmartupload control/method that loaded the image and it worked ...
UploadedInfo.Files.Item(1)
A for effort!!
If you are doing the former, I'd strongly suggest against it.
The following is a way to retreive the image "path".
[Assuming your database constant is "DB"]
<%
SQL = "SELECT Images WHERE ID = " & Request.QueryString("ID")
Set RS = DB.Execute(SQL)
Response.Write "<img src=""" & RS("ImagePath") & """>"
%>
Regards,
Wakie.