SqlConnection conn = new SqlConnection();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
byte[] arrContent ;
DataRow dr;
string strSql;
strSql = "Select Image from productItems where productid = 18";
da = new SqlDataAdapter(strSql, connectionString);
da.Fill(ds);
dr = ds.Tables[0].Rows[0];
arrContent = (byte[])dr["Image"];
Response.OutputStream.Write(arrContent,0,6306);
Response.End();
I am unable to write the bytes dat开发者_开发知识库a on my page which is actually an image. what I see is a series of special characters. what am i doing wrong?
I suspect you're trying to write the image straight into the HTML, where it doesn't belong. Your page should have an img
element which refers back to your server using a URL which will let you fetch the ID when that request comes in... and that's when you serve the actual image data, along with an appropriate content type.
Of course I may be off-base here... you haven't provided us any context (like what else is being served by this request...).
Other points:
- You should use a
using
statement on yourSqlConnection
so it gets closed whatever happens - I see no point in using a
DataSet
orSqlDataAdapter
. Why not just callExecuteReader
and then useGetBytes
to fetch the data? - You're always writing 6306 bytes to the response regardless of how much data there really is. Why?
You need to convert the byte array into a valid image and then display that image in web page.
C#: How to convert BITMAP byte array to JPEG format?
According to MSDN, "if no ContentType is specified, the default is text/HTML.". That means that when you are sending the image bytes, the browser considers it as an ordinary webpage, and tries to display it as it would display HTML content.
To avoid this behavior, you must explicitly set the content type to one of the MIME types specifying an image.
For example, for PNG images, you can use:
this.Response.ContentType = "image/png";
before sending actual content.
You need to covert what you have to string and render.
Response.ContentType = dRow["Image"].ToString();
byte[] imageContent = (byte[])((dRow["img_stream"]));
Response.BinaryWrite(imageContent);
Another way you can take is to use inline images (though not all browsers support it yet). Simple example:
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"
width="16" height="14" alt="embedded folder icon">
This will even optimize your site loading. You can read more about inline images here
精彩评论