Link to home
Start Free TrialLog in
Avatar of robossa
robossa

asked on

How to display an image from sql server DB in an ASP.NET image webcontrol

Hello! I know how to display using response.binary, but I need the image in a gif format to make it readable in a asp.net page. Thnaks. Robossa
Avatar of robossa
robossa

ASKER

I have a search file  for horses where I click a Imagebutton.url="index.aspx?para1=" + horseid

THEN

In the index.aspx file I have the code to read the binary field from database, but in an specific image tag . There is where I have the problem.
This sample should work :

Dim SQL
SQL = "Server=SQLServerName; Database=TestDB; uid=tester; pwd=1234;"
Dim Conn As New System.Data.SqlClient.SqlConnection(SQL)
Conn.Open()

SQL = "SELECT TOP 1 image_file FROM ImageTable WHERE horseid = " & Request.QueryString("para1")
Dim command As New System.Data.SqlClient.SqlCommand(SQL, Conn)
Dim reader As System.Data.SqlClient.SqlDataReader
reader = command.ExecuteReader()

If reader.HasRows Then
      While reader.Read()
              Response.Expires = 0
              Response.Buffer = True
              Response.Clear()
              Response.Charset = "utf-8"
              Response.ContentType = "image/gif"
              Response.BinaryWrite(reader("image_file"))
              Response.Flush()
        End While
Else
        Response.Write("No image found!")
End If
reader.Close()
reader = Nothing
Conn.Close()
Conn = Nothing
Response.End()
Avatar of robossa

ASKER

Bilson! As I said  the image is shown already but using  binary write. What I want is to place the image in an <img> tag, such as <img src=?????? border="1" />

Thnaks
if you want to display by <img> tag, you require to save your binary data in image file on your server anyway and reference it to src="/image.gif"
Avatar of robossa

ASKER

How do I save the binary data in an image file?
why don't you use

 <img src="showimage.aspx?para1=1" border="1" /> to show your binary image directly

from aspx where showimage.aspx is the script above.
Avatar of robossa

ASKER

Thanks. If there is not picture for para1=1 what would be the decision making code to add a picture of "not available".  
You can save your binary image as below

Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
Dim objStream
Dim FileName

FileName = reader("file_name"))
objStream = CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open()
objStream.Write(reader("image_file"))
objStream.SaveToFile(Server.MapPath ("/") & FileName , adSaveCreateOverWrite)
objStream = Nothing
response.write "<img src=""/""" &  FileName  & " border=""1"" />"

But I don't think it is good to store those duplicated files.
ASKER CERTIFIED SOLUTION
Avatar of billson
billson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial