2

I have a small app for taking a webcam image and putting this image into an sql database as binary data and that works fine. However i have a problem with a separate .net web page where i want to simply display the image on the page by the easiest means possible.

Here's some example code but its not much because I've being trying bits and bobs from the top of my head and just don't have a clue if I'm anywhere near the solution.

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["ConnectionString"];
        SqlConnection con = new SqlConnection(settings.ConnectionString);

        SqlCommand MyCmd;

        MyCmd = new SqlCommand("SELECT image FROM contractors WHERE number like @number", con);
        MyCmd.Parameters.AddWithValue("@number", "1");
        Image1 = MyCmd.ExecuteScalar();
    }

And to this i get the error message

Error 1 Cannot implicitly convert type 'object' to 'System.Web.UI.WebControls.Image'. An explicit conversion exists (are you missing a cast?)

But i don't know if I'm along the right lines so I've posted here not just specifically about that, but about what I'm trying to do overall.

3 Answers 3

5

You are assigning the result of the query directly to the Image variable - this will never work, since the Image control needs a URL in order to display an image on an ASP.NET page.

The most common approach is to write an Http Handler that will return the image data and use the handler URL as the ImageUrl.

See this MSDN page about Http Handlers, and this SO question on how to achieve what you are looking for.

Sign up to request clarification or add additional context in comments.

Comments

2

Use a base64 encoded data uri or use a url that will return the image data using Response.BinaryWrite. In your example, the Image1 variable will need to be a byte array and then you can Response.BinaryWrite it with the proper header set.

2 Comments

You need to test this with different browsers, according to en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support the max length in IE8 is 32Kb and if I recall correctly IE6 does not handle it at all.
True that. It states some of that in the link I posted and that's why I mentioned two possible ways to handle it.
1

1
Read the answer from Oded about how to get the image into the Image control

2

You can not get the image data with ExecuteScalar you need to do ExecuteReader

var reader = MyCmd.ExecuteReader();
if (reader.NextResult())
{
    byte[] imgData = (byte[])reader["image"];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.