PDA

View Full Version : Retriving image using SqlDataReader.


Zpixel
09-08-2009, 09:10 AM
I want to retrieve image from sql database in asp net:

string htmlResult="";

strSql = "Select * From products";
SqlCommand myCommand = new SqlCommand(strSql, con);
myCommand.ExecuteNonQuery();
SqlDataReader result = myCommand.ExecuteReader();

while (result.Read())
{
string name = Convert.ToString(result["name"]);

********
//problem! i don't know how to use result["picture"]
******************
picture= result["picture"];
htmlResult+="<div>" + picture + "<br>" + name + "</div>";
}

productTable.InnerHtml = htmlResult;

ghell
09-08-2009, 06:33 PM
It is possible to embed images directly into the web page I think. The acid tests such as Acid 3 (http://acid3.acidtests.org/) use this.

For example:
url(data:image/gif;base64,iVBORw0KGg...K5CYII%3D)

This example uses Base64, which you can get converted easily enough. It also seems to URLEncode it ("=" becomes "%3d").



You can also use System.Drawing to actually load the image yourself in a separate aspx file then just refer to that in your html.



It is far, far, far more common to store the images in the file system and just a path to them in the database.

Zpixel
09-09-2009, 10:07 AM
thanks.

i want to know, what should i convert the result["picture"] to?

type? picture=Convert.To?(result["picture"]);

ghell
09-09-2009, 12:57 PM
That depends what it is in the database. You don't want to use Convert either way. You almost always want to use ".Value" to start with at least.

If it is a BLOB in the database (such as varbinary) it should be a SqlBytes (http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqlbytes_members%28VS.80%29.aspx) type. SqlBytes.Value returns a byte[] which is much more useful.

If you wanted to create a .aspx page that returns that image you can then wrap a MemoryStream around that and just load it with System.Drawing.Image.FromStream to manipulate it or just pipe it straight to the Response.OutputStream and set a correct MIME type for the page.

If you wanted to use the CSS url(data: ... ) you could just use Convert to get it to Base64 and URLEncode it.


If it's actually a path to start with and the type is an SqlString, you can just use .Value to get the string and then use that in an <img src="..." /> tag or use an <asp:Image ... />

Zpixel
09-09-2009, 02:11 PM
it is binary data of an image. the column type is image. i have stored some pictures in it and want to retrieve it. it is an aspx page. it is not a path stored in db. it is just i dont know how to complete the code in order to prevent compilers error when i want to use that column.

ghell
09-09-2009, 02:15 PM
I have already told you how to do it if it is binary data.