如何使用处理程序显示图像的预览

时间:2011-07-01 12:44:31

标签: c# .net asp.net ado.net

我正在使用处理程序在我的页面上显示来自数据库的图像

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();
    }
}

此代码在从数据库显示图像时工作正常。 现在,我想要做的是使用不同的处理程序显示图像预览。 现在,如果您查看上面的代码,那么您可以看到我们有byte []形式的图像数据。 我上传了一个图像,我能够在byte []中获取数据,但是我的这个数据是在.cs页面上。

context.Response.BinaryWrite(imagethumbnail);

如果我使用此命令将数据从页面转换为字节,它会向我显示页面上的图像。 你能告诉我如何将这些数据显示到图像中吗?

数据流没有太大变化 这是我想要使用的,但是如何从.cs页面获取byte []到处理程序。

 imagethumbnail = MakeThumbnail((byte[])dReader["Image"], width, height);
        context.Response.BinaryWrite(imagethumbnail);

1 个答案:

答案 0 :(得分:3)

您可以将数据库图像逻辑分离为通用处理程序(ASHX),然后将处理程序用作图像的src,例如

<img src="GetImage.ashx?id=1"/>

你需要创建GetImage.ashx并适当地处理你的id(或任何你使用的)。然后你可以做一个简单的回写页面。

这将允许您在将图像用作页面上的单独元素时动态从数据库中提取图像。