I m using a handler to display images on my page from database
public void ProcessRequest (HttpContext context)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["XYZ"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select Image from EmployeeInfo where Emp_Id = @ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
int height = Convert.ToInt32(context.Request.QueryString["Ht"]);
int width = Convert.ToInt32(context.Request.QueryString["Wt"]);
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
if (dReader.HasRows)
{
dReader.Read();
byte[] imagethumbnail = null;
try
{
imagethumbnail = MakeThumbnail((byte[])dReader["Image"], width, height);
}
catch
{
}
context.Response.BinaryWrite(imagethumbnail);
}
dReader.Close();
con.Close();
}
public static byte[] MakeThumbnail(byte[] myImage, int thumbWidth, int thumbHeight)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
using (Image thumbnail = Image.FromStream(new MemoryStream(myImage)).GetThumbnailImage(thumbWidth, thumbHeight, null, new IntPtr()))
{
thumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}开发者_运维问答
This code works fine when displaying images from database. Now What I want to do is to Show image preview using a different Handler. Now if u look at the above code then you can see we have image data in byte[] form. I m uploading a image and I m able to get the data in byte[] but this data of mine is on .cs page.
context.Response.BinaryWrite(imagethumbnail);
If I use this command converting data into bytes from page, it shows me the image on page nothing else. Can you give me any idea how to show this data into image?
There is nothing much change in the datastream This is what I want to use but how to get byte[] from .cs page to handler.
imagethumbnail = MakeThumbnail((byte[])dReader["Image"], width, height);
context.Response.BinaryWrite(imagethumbnail);
You can seperate your database image logic into a Generic Handler (ASHX) and then use the handler as your image's src
e.g.
<img src="GetImage.ashx?id=1"/>
You'd need to create GetImage.ashx and handle your id's (or whatever your using) appropriately. Then you can do a simple write back to the page.
This will allow you to dynamically pull an image from the database while using it as a seperate element on your page.
精彩评论