Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从数据库中检索图像并显示在网页上_C#_Asp.net_Sql Server_Winforms - Fatal编程技术网

C# 从数据库中检索图像并显示在网页上

C# 从数据库中检索图像并显示在网页上,c#,asp.net,sql-server,winforms,C#,Asp.net,Sql Server,Winforms,我使用以下代码将面板另存为数据库中的图像: public Form2() { InitializeComponent(); } public static byte[] ImageToByte2(Bitmap img) { byte[] byteArray = new byte[0]; using (MemoryStream stream = new MemoryStream()) { img.Save(stream, System.Drawi

我使用以下代码将面板另存为数据库中的图像:

public Form2()
{
    InitializeComponent();
}

public static byte[] ImageToByte2(Bitmap img)
{
    byte[] byteArray = new byte[0];

    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();

        byteArray = stream.ToArray();
    }

    return byteArray;
}

private void button1_Click(object sender, EventArgs e)
{
    Form1 fom = new Form1();

    Bitmap bitmap = new Bitmap(fom.panel1.ClientSize.Width,
                          fom.panel1.ClientSize.Height);

    fom.panel1.DrawToBitmap(bitmap, fom.panel1.ClientRectangle);

    byte[] imgArray = ImageToByte2(bitmap);

    ImageData img = new ImageData
    {
        ClassName = textBox1.Text,
        Password = textBox2.Text,
        Image = imgArray,
    };

    using (BoardDatabaseEntities dc = new BoardDatabaseEntities())
    {
        dc.ImageDatas.Add(img);
        dc.SaveChanges();
        MessageBox.Show("Saved into database");      
    }

    this.Close();
}

我正在尝试在网页(视图控制)上显示数据库中的图像,但尚未成功。互联网上有很多源代码,但它们都上传了一个文件。代码用于
上载文件
。我就是想不出如何使它(那些代码)适合我的情况。您能提供帮助吗?

一种解决方案是将字节数组转换为base64编码字符串,然后将其发送到视图


通常的做法是,您有某种处理程序从数据库检索图像并将其提供给客户端。为了知道要检索的图像,您需要主键。为了提供正确的MIME类型,您需要从数据库中提取该数据

将通用处理程序(.ashx)添加到项目中

public class Handler : IHttpHandler
{

    public void ProcessRequest (HttpContext context)
    {

        string ImageId = context.Request.QueryString["Id"]; //you'll want to do defensive coding and make sure this query string variable exists



        byte[] ImageBytes = Database.GetImageBytes(ImageId); //I assume you know how to retrieve the byte array from the database?
        string MimeType = Database.GetMimeType(ImageId);

        context.Response.ContentType = MimeType;
        context.Response.BinaryWrite(ImageBytes);
    }

    public bool IsReusable { get { return false; } }
}
然后在页面上,您只需将URL放入图像源的处理程序

<asp:Image runat="server" ImageUrl="~/RetrieveImage.ashx?Id=505874" />