HttpHandler问题,检索图像

时间:2012-08-14 17:37:26

标签: c# asp.net image listview httphandler

以下HttpHandler是从数据库中检索图像。当我最初测试它时工作正常。但现在的问题是它仍然可以提取图像,但不会在Listview中的图像控件中显示它。

    `public void ProcessRequest (HttpContext context) 
{
    string imageid = context.Request.QueryString["ImID"];
    using (SqlConnection connection = ConnectionManager.GetConnection())
    {
        SqlCommand command = new SqlCommand("select Normal_Thumbs from User_Images where Id=" + imageid, connection);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        if (dr[0] != DBNull.Value)
        {
            Stream str = new MemoryStream((Byte[])dr[0]);

            Bitmap Photo = new Bitmap(str);
            int Width = Photo.Width;
            int Height = Photo.Height;
            int imagesize = 200;
            if (Photo.Width > Photo.Height)
            {
                Width = imagesize;
                Height = Photo.Height * imagesize / Photo.Width;
            }
            else
            {
                Width = Photo.Width * imagesize / Photo.Height;
                Height = imagesize;
            }

            Bitmap bmpOut = new Bitmap(150, 150);

            Graphics g = Graphics.FromImage(bmpOut);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.FillRectangle(Brushes.White, 0, 0, Width, Height);
            g.DrawImage(Photo, 0, 0, Width, Height);

            MemoryStream ms = new MemoryStream();
            bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] bmpBytes = ms.GetBuffer();
            bmpOut.Dispose();
            ms.Close();

            context.Response.Write(bmpBytes);

            context.Response.End();

        }
    }
}

处理程序检索图像,但列表视图不显示它。

1 个答案:

答案 0 :(得分:0)

尝试这种方法,将内容类型设置为响应。

...
    context.Response.Clear();
    context.Response.ContentType = System.Drawing.Imaging.ImageFormat.Png.ToString();
    context.Response.OutputStream.Write(bmpBytes, 0, bmpBytes.Length);             
    context.Response.End(); 
...

问候。