使用Generic Handler的动态图像(来自db)

时间:2010-02-09 17:57:39

标签: c# asp.net

我正在尝试使用Generic Handler来检索和显示存储在数据库中的图像。

但它只是不起作用。我已经尝试了下面的代码,但我似乎无法让它工作。

Anyonne能否发现我做错了什么,或者有什么建议?

<%@ WebHandler Language="C#" Class="IconsDb" %>

using System;
using System.Web;
using System.Linq;
using System.Data.Entity;

public class IconsDb : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
        Int32 iconId;

        if (context.Request.QueryString["id"] != null)
            iconId = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/gif";
        //System.IO.Stream strm = ShowEmpImage(iconId);

        var db = new UdINaturen.UdINaturenContext();

        var GetIcon = (from i in db.subcategoryicons
                       where i.id == iconId
                       select i.picture).FirstOrDefault();
        object img = GetIcon;

        System.IO.MemoryStream memStream= new System.IO.MemoryStream((byte[])Convert.FromBase64String(GetIcon));
        System.Drawing.Bitmap bitImage=new System.Drawing.Bitmap((System.Drawing.Bitmap)System.Drawing.Image.FromStream(memStream));


        byte[] buffer = memStream.ToArray();
        context.Response.ContentType = "image/gif";
        //context.Response.OutputStream.Write(buffer, 0, buffer.Length);
        //context.Response.WriteFile();
        context.Response.BinaryWrite(buffer);
        //context.Response.Flush();


    }





    public bool IsReusable {
        get {
            return true;
        }
    }

}

1 个答案:

答案 0 :(得分:3)

哇,好的。不知道有多少是旧代码,应该注释掉的内容还是w / e,但尝试这样的事情:

public void ProcessRequest (HttpContext context) {
    int iconId;

    if (string.IsNullOrEmpty(context.Request.QueryString["id"]) || !int.TryParse(context.Request.QueryString["id"], out iconId) )
        throw new ArgumentException("No parameter specified");

    context.Response.ContentType = "image/gif";

    var db = new UdINaturen.UdINaturenContext();

    var GetIcon = (from i in db.subcategoryicons
                   where i.id == iconId
                   select i.picture).FirstOrDefault();
    byte[] buffer = (byte[])Convert.FromBase64String(GetIcon);

    context.Response.ContentType = "image/gif";
    context.Response.BinaryWrite(buffer);
    context.Response.Flush();
}