【问题标题】:Retrieve an image from databse and display on webpage从数据库中检索图像并显示在网页上
【发布时间】:2015-10-08 21:31:27
【问题描述】:

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

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

我正在尝试在网页上显示数据库中的图像(视图控件),但还没有成功。互联网上有很多源代码,但它们都上传了一个文件。代码用于UploadedFile。我只是不知道如何使它(那些代码)适合我的情况。你能帮忙吗?

【问题讨论】:

    标签: c# asp.net sql-server winforms


    【解决方案1】:

    一般的做法是您有某种处理程序,可以从数据库中检索图像并将它们提供给客户端。为了知道要检索什么图像,您需要主键。为了提供正确的 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" />
    

    【讨论】:

      【解决方案2】:

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

      Converting image into data:image/png;base64 for web page disaplay

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多