blah blah blah is here! blah blah » Close

up0down
link

Hi,

I have binary data in my sql database that is of type image. Now I want to load this binary data to an image, have you any idea how I could do this?

Thanks.

last answered 2 years ago

2 answers

up0down
link

Anyone?

up1down
link

Something like this:

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("select image from table where id=1", conn); // or whatever
byte[] blob = (byte[])cmd.ExecuteScalar();
MemoryStream ms = new MemoryStream();
ms.Write(blob, 0, blob.Length);
Image img = Image.FromStream(ms);
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); // EDIT extra line added
conn.Close();

sanjib
226

vulpes, does this retrieve any perticular image (whose ID=1)from database? If that so, then can I take that ID from any TextBox and put it in DML? Can that be done?

vulpes
17279

This is just intended as a specimen 'select' query where you select a field called 'image' from a record in 'table' whose 'id' field contains 1. But, yes, you could take the id from a textbox and embed that into the query. If 'id' is a string rather than an integer in the database, then you'll need to surround it with single quotes, of course.

s1nn0n
0

Thanks for that, although I am getting the following error: Cannot implicitly convert type 'System.Drawing.Image' to 'System.Web.UI.WebControls.Image' for Image1 = System.Drawing.Image.FromStream(ms); I have directly referenced it to System.Drawing.Image as it didnt know whether to use that or using System.Web.UI.WebControls; Any ideas? Thanks.

vulpes
17279

If it's an ASP.NET application, then I think you'll need to save the image to a file first. You can then load it into a 'System.Web.UI.WebControls.Image' control by setting its ImageURL property to the file path. I've edited my answer to include an extra line to save the image to a file. The 'Image' class in the code is the System.Drawing.Image class, as you surmised.

Feedback