Tuesday, March 13, 2012

The image cannot be displayed, because it contains errors.

I have a code in photo.aspx.cs as follows to display image in browser (photo.aspx does not have any space or markup, only @dotnet.itags.org. Page directive):

protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "image/bmp";

string employeeID = Request.QueryString["EmployeeID"];
string sqlText = "SELECT Photo FROM Employees WHERE EmployeeID = " + employeeID;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString());
SqlCommand command = new SqlCommand(sqlText, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
Response.BinaryWrite((byte[])dr["Photo"]);
}
connection.Close();
Response.Flush();
Response.Close();
}

Now when I access this page as http://localhost:4538/WebSite12/photo.aspx?EmployeeID=1 in firefox, it gives following error. Can someone help me to sort out this problem please?

The image "http://localhost:4538/WebSite12/photo.aspx?EmployeeID=1" cannot be displayed, because it contains errors.

Hi,

How about this one, which is from http://davidhayden.com/blog/dave/archive/2006/07/25/SavingDisplayingPhotosInSQLServerUsingASPNET.aspx

protectedvoid Page_Init(object sender, EventArgs e){if (Request.QueryString["id"]!=null) {int id;if (Int32.TryParse(Request.QueryString["id"],out id)) { Response.Clear(); Response.ContentType="image/jpeg"; Image image= RetrieveImage(id); image.Save(Response.OutputStream, ImageFormat.Jpeg); } }}private Image RetrieveImage(int photoId){ Image image=null;using (SqlConnection connection=new SqlConnection("...")) {using (SqlCommand command= connection.CreateCommand()) { command.CommandText="SELECT Photo FROM Photos
WHERE PhotoId = @.PhotoId"; command.Parameters.AddWithValue("@.PhotoId", photoId); connection.Open();byte[] imageData= (byte[])command.ExecuteScalar(); MemoryStream memStream=new MemoryStream(imageData); image= Image.FromStream(memStream); } }return image;}
 

0 comments:

Post a Comment